[Part III]Control Flow in Python🐍

[Part III]Control Flow in Python🐍

Let's explore conditionals and loops

Welcome back to the series "Learn Python with me!"👋👋

We really have come far. Last time we learned about Operators and their precedence. Remember, giving a parenthesis even when you know that it will be taken care of, by the precedence of operators, is always better. We know about constants that do not change throughout the course of the program.

Is the random generation in Python really that random?

No, right! It is pseudo-randomness that we see.

We had checked how a lot of operators were giving us bool values(that is, True/False). These relations take us right into our next topic - Control flow.

What is Control flow?

This refers to how the program is executed. Until now, we were writing programs that were being followed line-by-line by the interpreter(sequential flow). The control flow in Python is regulated by conditional statements, loops, and function calls.

We will be breaking these down into parts and diving further into them.

Conditionals

We had seen a lot of boolean values, before when tackling operators. These can be used in conditional statements. The program basically runs based on some Boolean conditions.

The keywords are if, else, elif.

The basic if-else structure goes something like this👇

if condition:
    body
else:
    body

The program first encounters the if statement. It checks the condition present. If the answer is True , the body of the if statement is executed, after which it skips the else part and moves on to the rest of the program.

If the answer to the condition is False, the control moves to the else part and executes whatever is within it.

We will be able to understand this better, with an example.

Let's try a simple(a little silly) program first. We will check if the user gives zero as input and then display 0, otherwise display not 0.

def main():
    #Take input from user
    num = input("Enter the number in words: ")
    #Check whether the input was - zero
    if num == "zero":
        print("0")
    #In case input was not zero,run the else part
    else:
        print("not 0")

if __name__ == '__main__':
    main()

Let's run the program and check both scenarios.

2021-05-07 (3).png

2021-05-07 (4).png

Let's get to the elif part. elif is actually else-if. We can use another condition with this part. There can be multiple elif statements, after if and before else.

Let's check whether a number is negative, positive, or equal to zero.

def main():
    num = int(input("Enter number: "))
    if num == 0 :
        print("Equal to zero.")
    elif num>0 :
        print("Number is positive")
    else:
        print("Number is negative ")

if __name__ == "__main__":
    main()

Use different values to check the results.

We can also have nested conditional statements. We will understand what this means, with the help of a problem.

We will tweak the above program a little bit. If the number is positive, we must check whether it is odd or even. If the number is negative, we will check if it is divisible by 3 and display it if True, otherwise, we do nothing.

def main():
    num = int(input("Enter number: "))

    if num == 0 :
        print("Equal to zero.")

    elif num>0 :
        if num%2 == 0:
            even_or_odd = "even"
        else:
            even_or_odd = "odd"
        print("Number is positive and " + even_or_odd)

    else:
        if num%3 == 0:
            print("Divisible by 3")
        print("Number is negative ")

if __name__ == "__main__":
    main()

Conclusions from this program:

  • Any part of the program, be it within if, elifor else, we can have another set of conditionals.

  • Indentation becomes important to deal with here. Keeping your programs well-spaced and neat, will help you understand them better.

  • This is obvious, but conditional statements can have multiple statements within.

Note: Without elif you could have another if, and it would not bring any change to your output, but the program would have to check every if statement. Here in the if-elif-else stack, we do not necessarily have to check every condition all the time.

Loops

Some tasks have to be repeated continually. For example, if we have to print the even numbers from 0-100, we would have to write 50 print statements! That is a complete waste of time and is not logical at all.

Hence we have loops.

There are two types of loops in Python:

  • while loops.
  • for loops

Let's take a look at while loops first.

The basic syntax is:

while condition_is_true:
    body

Whenever we start a loop, there is a precondition and a postcondition.

The precondition is the state in which the program is before it encounters the loop. In the case of a while loop, we have a condition. When the condition is True the first time, it enters the loop and executes the body. It again checks the condition, if it is still True the loop will run again. Once the condition becomes False, the control moves out of the loop. The state of the program might have changed, in other words, the postcondition might not be the same as the precondition.

Let's take a problem. My first programming language was actually Java. This was our first example of while loops.👇

Write a program that takes numbers of the user, until the user gives -1, then the program prints the total of all the other numbers.

We will think through the problem and then write the program.

✔ We can see that the program takes input from the user. We are experts at it!

✔ In the end, we need the sum of all the numbers, you might be thinking of a variable( a box), containing the sum.

✔Now, the new challenge is keeping on taking input from the user until they give -1.

Do you feel like this might be our condition? Until the input is -1

We saw earlier that we can use a while loop to keep doing a repetitive task until the condition becomes False.

We have formed our basic skeleton now. Let's code it.

def main():
    # sum will store our total value
    sum = 0
    # the loop checks the condition with num first, hence we take the input for the first number here
    num = int(input("Enter a number: "))
    #start of the while loop
    while num!=-1:
        #updating the sum with the new number
        sum = sum + num
        #taking the other subsequent numbers
        num = int(input("Enter a number: "))
    #finally when the user enters -1, we print the total
    print("The total is : "+str(sum))

if __name__ == "__main__":
    main()

Let's run our program and see if it works!

2021-05-07 (7).png

It does work!

Now that we are familiar with the while loop, let's see what the for loop is all about.

The for loop repeats a task a specific number of times. Say, we need to write "Expelliarmus" 100 times. (Something for you Potterheads out there!😁)

def main():
    for i in range(100):
        print("Expelliarmus")

if __name__ == '__main__':
    main()

If we look at it from far away, it looks like we could just write how many times we want the task to be repeated within the parenthesis and it repeats it for us.

Now let's understand what is happening on a deeper level.

The first question that might arise might be - What is i ?

i is a counting variable that keeps track of the number of times the loop has run.

for loop when converted to a while loop looks like this👇

i = 0
while i < 100:
   print("Expelliarmus")
   i += 1

We initialize i with 0. The while loop runs until i is less than 100(0-99 means 100 times). Inside the loop, we increment it by 1 so that it keeps on running.

This whole thing gets reduced to a single line in a for loop, making our program shorter and more concise.

Let's try a bunch of ways we can use the for loop.

Say, we need to print the numbers from 1-10. Here's how we write the for loop.

def main():
    for i in range(1,11):
        print(i)

if __name__ == "__main__":
    main()

Run this program.

Some important observations are:

  • for i in range(1,11) -> runs from 1 to 10 ( that means it excludes the last number from the range).

  • print(i) -> We can use the i variable inside the loop.

Say, we need to print all the even numbers from 1 to 20. We could do it in various ways. I will list some here.

def main():
    for i in range(1,21):
        if i%2 == 0:
            print(i)

if __name__ == "__main__":
    main()

OR

def main():
    for i in range(2,22,2):
        print(i)

if __name__ == "__main__":
    main()

In the last program, i goes from 2 to 22(excluding 22), and skips 2 numbers at a time.

These are ways in which for loops work.

Now, we come to another interesting topic 👇

Nested Loops

Loops, just like if-elif-else stack can be nested.

See the program below.

def main():
   print('i','j')
   for i in range(2):
       for j in range(3):
           print(i,j)

if __name__ == "__main__":
    main()

Observations:

  • i and j are the two counting variables.

  • The first loop is called the outer loop, and the second one is called the inner loop. (Check the indentation, you will understand why)

Now let us see the result in our terminal.

2021-05-08 (2).png

Let's analyze this:

  • First, we print i j, remember the comma in print, gives a space(we did this to be clear about whose values are being printed.
  • Next, we encounter the outer loop. i will take values [0,1]. Now, the value is 0.

  • It goes into it's body where it encounters the inner loop. j will take on values [0,1,2].

  • The inner loop runs 3 times, and prints i and j values.(Note that the whole thing occurred while i was 0.

  • Now, the loop goes back, and i takes on the value 1. After which j runs the usual way and prints the values.

When do we use while and when do we use a for loop ?

We use the while loop when we do not know how many times the program will run, but are aware of the conditions under which the program needs to stop.

We use for loop when we know the number of times the program will run. In other words, we know the values to put inside range(), so as to get the desired result.

Nothing we learn is productive, until and unless we can put it to practice.

We will tackle another very famous problem. "Guess my number". In this problem, the program generates a random number between 0-100, the user needs to guess it. The program informs the user whether the number the user guessed is too low or too high accordingly.

💡Let's gather some points before jumping into coding.

✔We need to generate a secret random number. Think about the random number generator.

✔We need to keep checking whether the user has guessed it correctly or not. This is a repetitive task and we do not know the number of times the user will have to guess before coming to the correct answer. Think about what we are going to use.

✔We need to check what the user guesses and give the appropriate hints. Looks like we need to use conditional statements.

Let's start coding!

import random

def main():
    secret_number = random.randint(0, 100)
    print("I am thinking of a number between 0 and 100...")
    guess = int(input("Enter a guess: "))

    while guess != secret_number:
        if guess < secret_number:
            print("Your guess is too low")
        else:
            print("Your guess is too high")
        print("") # an empty line
        guess = int(input("Enter a new guess: "))
    print("Congrats! The number was: " + str(secret_number))

if __name__ == '__main__':
    main()

Let's play the game and check if you guessed it before me!

2021-05-08 (4).png

We discussed conditionals and loops in this segment. Next, we will be delving into functions and having some fun there. You can ask any questions in the comments below. Let's help each other grow📈!

Next part coming soon!

Happy Learning!