Learning Python Part-22: Python Flow Control

Before we go ahead and discuss about python flow control using if statements, for loop and while loop. Let’s understand Python indentation quickly.

Python Indentation:

  • Programming languages like C, C++, Java use braces { } to define a block of code. 
  • However, Python uses indentation to define the code block. 
  • Indentation basically means, use of whitespaces.
  • Generally 4 whitespaces (4 times space bar) are used for indentation & it is preferred over tabs. 
  • Tabs also can be used instead of whitespaces. However,  make sure that it’s not mixture of tabs and whitespaces. Use any one of it.
  • The amount of indentation is up to user, but it must be consistent throughout the code block.

Example:

If True:
    print(“Hello”)

  • Indentation in Python makes the code look neat and clean. 
  • Above code can also be written on single line as 

if True: print(‘Hello’)

  • This results into Python programs that look similar and consistent.
  • Incorrect indentation will result into IndentationError.

Python Flow Control using : If… statement

  • Decision making is required when we want to execute a piece of code only if a certain condition is true.
  • The if…elif…else statement is used in Python for decision making.
  • Syntax:

if testexpression:
    statement(s)

  • In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.
  • Python interprets non-zero values as True. None and 0 are interpreted as False.

# If the number is positive, print an appropriate message
num = 3

if num > 0:
   print(num, “is a positive number.”)


Python Flow Control: If… else

  • Syntax:   
if testexpression:
     Body of if
else:
     Body of else

  • Example:

num = 3
if num >= 0:
   print(“Positive or Zero”)
else:
   print(“Negative number”)  


Python Flow Control: If…elif… else

  • Syntax:

if testexpression:
    Body of if
elif test expression:
    Body of elif
else:
    Body of else

  • Example:

num = 3
if num > 0:
    print(“Positive number”)
elif num == 0:
    print(“Zero”)
else:
    print(“Negative number”)


Python Nested if statements:

We can have a if…elif…else statement inside another if…elif…else statement.  This is called nesting in computer programming. Any number of these statements can be nested inside one another.

  • Indentation is the only way to figure out the level of nesting. 
  • This can get confusing, so should be avoided if we can.
  • Example:

num = int(input(“Enter a number: “))
if num >= 0:
    if num == 0:
        print(“Zero”)
    else: 

        print(“Positive number”)
else: 
     print(“Negative number”)

Python for Loop:

  • The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. 
  • Iterating over a sequence is called traversal.
  • Syntax of for Loop

for var in sequence:
      Body of for

  • Here, var is the variable that takes the value of the item inside the sequence on each iteration.
  • Loop continues until we reach the last item in the sequence. 
  • The body of for loop is separated from the rest of the code using indentation.
  • Example:

# Program to find the sum of all numbers stored in a list

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
add = 0

for x in numbers:
      add = add+var
      print(“The sum is”, add).

# Output will be 48


for loop with else:

  • A for loop can have an optional else block as well. 
  • The else part is executed if the items in the sequence used in for loop exhausts.
  • Example: 

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints

digits = [0, 1, 5]

for i in digits:
      print(i)
else:
      print(“No items left.”)

Output:
0
1

No items left.

How for loop actually works?


As we have seen in the above examples, the for loop was able to iterate automatically through the list. In fact the for loop can iterate over any iterable. 
Let’s take a closer look at how the for loop is actually implemented in Python.

for element in iterable:              

       do something with element
This is actually implemented as.

iter_obj = iter(iterable)                                  # create an iterator object from iterable

while True:                                                    # infinite loop
           try:
               element = next(iter_obj)                # do something with element

           except:
                StopIteration:                                # if StopIteration is raised, break from loop
                break
  • So internally, the for loop creates an iterator object, iter_obj by calling iter()on the iterable. 
  • Ironically, this for loop is actually an infinite while loop.
  • Inside the loop, it calls next() to get the next element and executes the body of the for loop with this value. 
  • After all the items exhaust, StopIteration is raised which is internally caught and the loop ends. 
  • Note that any other kind of exception will pass through

Python while Loop:

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don’t know beforehand, the number of times to iterate.

Syntax:
while testexpression: 
         Body of while

  • Body starts with indentation and the first unindented line marks the end.
  • Python interprets any non-zero value as True. None and 0 are interpreted as False.

Example:

# Program to add numbers upto n numbers

n = int(input(“Enter number: “))
add = 0
i = 1

while i <= n:
      add = add + I

      i += 1

print(“The sum is”, add)
Output:

Enter number: 10

The sum is 55


while loop with else:

  • Same as that of for loop, we can have an optional else block with while loop as well.
  • The else part is executed if the condition in the while loop evaluates to False.

Example:

counter = 0
while counter <= 3:
        print(“we are inside the loop”)
        counter = counter + 1
else:
       print(“We are now in else statement”)

Output:

we are inside the loop
we are inside the loop 

we are inside the loop 
we are inside the loop
We are now in else statement

The range() function:

  • We can generate a sequence of numbers using range() function. 
  • The range(10) will generate numbers from 0 to 9 (10 numbers).
  • We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided.
  • This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
  • To force this function to output all the items, we can use the function list().

Example:

print(range(10))                                        
print(list(range(10)))  
print(list(range(2, 8)))                      #  Starting from 2 till (8-1)
print(list(range(2, 20, 3)))                #  Start from 2 to (20-1) stepping 3 at a time

Output:

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17] 
  • We can use the range() function in for loops to iterate through a sequence of numbers
  • It can be combined with the len() function to iterate though a sequence using indexing.

Example: In below example, we have three strings elements in a list. That basically means we do not have, how many iterations. So we count length of list (3 elements) and use it as range number.


sport = [‘cricket’, ‘chess’, ‘carrom’]

for i in range(len(sport)):                      # iterate over the list using index
        print(“I do like”, sport[i])

Output:

I do like cricket
I do like chess 

​I do like carrom

Python break Statement:

  • Loops iterate over a block of code until test expression is false, but sometimes we might want to terminate the current iteration or even the whole loop without checking test expression.
  • The break statement is used in these cases.
  • The break statement terminates the loop containing it. 
  • Control of the program flows to the statement immediately after the body of the loop.
  • If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

Example:



Python continue statement:

  • The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
  • Loop does not terminate but continues on with the next iteration.
Example:


Python pass statement:

  • In Python programming, pass is a null statement. 
  • The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
  • However, nothing happens when pass is executed. It results into no operation (NOP).

Example:



  • We can do the same thing in an empty function or class as well.

def function(args):
      pass 


class example():
      pass

Leave a Reply