Python Program Flow Control

The order in which python program codes will execute called python program flow control, the flow control has been regulated by the loops, statements and function calls.

In python, the flow controls are divided into three types:

Selection Statements:
  • If
  • If else
  • if-elif-else
  • if-elif
Interactive Statements
  • for
  • while
Transfer Statements
  • break
  • continue

if Statement

If statement accepts a boolean value or expression which results in a boolean value, based on this boolean value if statement decides whether to execute the following block or not

If the condition is true then python will run the code present in the if block otherwise python will skip the

if block.

In python, we are going to define the if statement by using the if keyword and with colon and then indentation.

Indentation is nothing but whitespace which specifies the scope in the code, in other programming languages we often use curly bases instead of whitespaces.

Following example demonstrates a simple if statement

a=23
b=56
if b>a:
    print("b is greater than a")

#The output of the above program is 
b is greater than a

If we try to execute the above program without indentation, then python will throw an indentation error

a=23
b=56
if b>a:
print("b is greater than a")

python-flow-control-one

The following example will demonstrate clearly about if condition statement

name=input("Enter Name:")
if name=="Ash":
    print("Hello Ash good morning")
    
print("How are you")

python-flow-control-two

In the above example, the if statement contains only one condition if name==Ash, if this condition is true then python will print "Hello Ash good morning" along with "How are you".

The condition for if statement is false then python will come out of if condition and prints only "How are you".

python-flow-control-three

Python Datatype summary

if-else Statement

The else means instead of or beside.

When the condition for if statement is false then we use else block to execute the statement/expression

Either if block or else block got executed but not both the statements

The syntax for if else statement is

if condition
    #executes this block if this condition is true
else:
   #execute this block if the condition is false

The following example demonstrates if else statement

name=input("Enter Name:")
if name=="Ash":
    print("Hello Ash good morning")
else:
    print("Hello good evening")
print("How are you")

The condition for if statement is true then the output is as below python-flow-control-four

And, The condition for if statement is false then the output is as below

python-flow-control-five

Python string Datatype

if elif else Statement

The else if in short is called as elif, the elif condition checks for multiple loops, if the condition for if statement is false then, python will check for the elif block, if the condition of all the elif is false then the body of else condition is executed.

The if elif else statement contains only one else block but it can have any number of elif blocks.

The syntax of if elif else Statement

#syntax
if test expression:
#body of if
elif test expression:
#body of elif
else:
#body of else

Following example demonstrates the if elif else statement

branch=input("Enter your favorite branch:")
if branch=='CS':
    print("It is software branch")
elif branch=='EE':
    print("It is electrical branch")
elif branch=='Mech' :
    print("It is hardware branch")   
else:
    print("Other branches are not recommended")    

If the condition for if statement is true then the output is as below:

python-flow-control-six

If I enter the favorite branch as EE then the output is as below

python-flow-control-seven

If the condition for if statement is false then python will execute the else block and prints the output as other branches are not recommended.

python-flow-control-eight

Following example to find the biggest of two numbers

a=int(input("Enter First number:"))
b=int(input("enter Second number:"))
if(a>b):
    print("Biggest number:",a)
else:
    print("Biggest number:",b)    

If the condition a>b is true then the output is as below:

python-flow-control-nine

And, if the condition a>b is false then the out is as below:

python-flow-control-ten

The following program to find the biggest number from the three given numbers

a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if a>b and a>c:
    print("Biggest number:", a)
elif b>c:
    print("Biggest number:", b)
else:
    print("Biggest number:")

If a>b and a>c then the output is

python-flow-control-eleven

And, if b>c condition is true then the output is

python-flow-control-tweleve

If the if condition and elif conditions are false then python will execute the elseblock and the output is

python-flow-control-thirteen

The Following program is to check whether the given number is between 1 to 100 or not

n=int(input("Enter some number:"))
if n>=1 and n<=100:
    print("The number {} is in between 1 and 100".format(n))
else:
    print("The number {} is not in between 1 and 100".format(n))

python-flow-control-fourteen

If the number is not in between 1 and 100 then, the output is

python-flow-control-fifteen

Following example to take a single-digit number from the keyboard and print its value in the English word

n=int(input("Enter digit from 0 to 9:"))
if n==0:
    print("Zero")
elif n==1:
    print("One")
elif n==2:
    print("Two")
elif n==3:
    print("Three")
elif n==4:
    print("four")
elif n==5:
    print("Five")
elif n==6:
    print("Six")
elif n==7:
    print("Seven")
elif n==8:
    print("Eight")
elif n==9:
    print("Nine")
else:
    print("Please enter a digit form 0 to 9 only")     

The output is

python-flow-control-sixteen

If the input is 15 then the output is

python-flow-control-seventeen

Instead of using the so many elif statements we can shorten the above program by using the List

n=int(input("Enter digit from 0 to 9:"))
words=['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
print(words[n])
             

python-flow-control-eighteen

Python Bytes and Bytearray

Iterative Statements

A rule which applies repeatedly on any condition or statement is called Iterative.

In python, If we want to execute a group of statements multiple times then we are going to use Iterative statements.

Python supports two types of iterative statements

for loop

For every element present in the collection or sequence if you want to perform any activity then we are going to use for loop.

ex: for every x in the sequence to perform some activity, which means every element which is present in the sequence, where the sequence may be a list, tuple, set, string, range, or dict.

And the activity can be performed multiple times on these sequences.

Syntax of for loop

for x in sequence:
   activity

Following example to print every element present in the string

s="ICE Cream"
for x in s:
    print(x)
    

The output is for-loop-one

The following example to print the character with an index which is present in the string

s="Banana"
i=0
for x in s:
    print("The character present at {} index: {}".format(i,x)) 
    i=i+1

for-loop-two

In the above program, I am modifyings ass=input("Enter any string") , when we enter the name dynamically from the keyboard then, python will print the string characters with index as below

s=input("Enter any string")
i=0
for x in s:
    print("The character present at {} index: {}".format(i,x)) 
    i=i+1

And hence the output is

for-loop-three

Applications using for loop

The following example is to print the given statement 10 times for that we can make use of range data type.

We have three forms of range of data types :

range(n): Is always going to represent the numbers from 0 to n-1

range(m,n): Represent the numbers from m to n-1

range(m,n increment-decrement): This will represent the numbers from m to n-1 with increment-decrement.

Print welcome to python for loop ten times

for x in range(10):
    print("Hello welcome to python for loop")

for-loop-four

The next program is to print the numbers from 1 to 10

for x in range(1,11):
    print(x)

for-loop-five

Following example is to print odd numbers from 0 to 20

for x in range(21):
    if x%2 != 0:
        print(x)
    

The output is

for-loop-six

Another alternative to print the odd numbers from 1 to 20 is, by considering the range between 1 to 21 and every time increasing value by 2 that means range(1,21,2)

for x in range(1,21,2):
    print(x)
    

for-loop-seven

Following example to print numbers from 1 to 10 in descending order, for this, we are using the third form of range datatype as the range is between 10 to 0 and every time the value is decreasing by -1.

for x in range(10,0,-1):
    print(x)
    

for-loop-eight

The following example is to print the sum of given numbers in the list, but here the list function is always going to return the string datatype and hence we have to use the eval() function to print the given values.

List = eval(input("Enter some list of number:"))
sum=0
for x in List:
    sum=sum+x 
    print("The sum:",sum)

The output is

for-loop-nine

Command Line Arguments

while loop

While loop is used to execute some statement as long as the condition is True, the while loop is mainly based on some condition.

The syntax of while loop is

while condition:
  # code block

Applications of while loop

1. Following example is to print welcome message ten times by using a while loop

i=1
while i<=10:
    print("Hello, welcome to python while loop")
    i=i+1

The output is:

while-loop-two

Next example is to print the sum of first n numbers

n=int(input("Enter number:"))
sum=0 
i=1 
while i<=n:
    sum=sum+i 
    i=i+1 
print("The sum of first",n,"numbers is :",sum)

And the output of the first 5 number is

while-loop-three

Python Input and Output Statements

Infinite loop

The infinite loop means an endless loop, In python, the loop becomes infinite loop until the condition becomes false, here the code will execute infinite times if the condition is false.

The following example is to demonstrate the infinite loop

i=0; 
while True : 
    i=i+1; 
    print("Hello",i)

The I value keeps on incremented by 1 each time and hence python will execute an infinite loop

infinite-loop-one

Python Modules

Nested loop

The loops inside another loop are called as nested loops.

The following example demonstrates the Nested loop

for i in range(3):
        for j in range (2):
                       print("Hello")

The output is:
when i=0
 then j=0 and print Hello
         j=1 and print Hello
when i=1
then j=0 and print Hello
        j=1 and print Hello
 when i=2
then j=0 and print Hello
        j=1 and print Hello

The above program contains two for loops, in the outer for loop, forI in the range(3) means, whenever I value is 0,1, and 2 pythons will execute the loops and print Hello.

And in the inner for loop, for j in the range(2), that means whenever the j value is 0,1, and 2 then python will execute the loop and print Hello.

nested-loop-one

Whenever i=0, i=1, and i=2 the Hello has printed totally 6 times.

Python Mutability

Transfer statements

The transfer is nothing but moving an object from one place to another place.

In python, transfer means, transferring the control from one condition to another condition we use transfer statements.

There are two types of transfer statements in python

  • Break statement
  • continue statement

Python Operator

Break statement

The break is nothing but dividing into one or more parts/pieces.

In python, the break statement is used inside the loops to break the current loop and resumes it in another loop based on some condition.

The syntax of thebreakstatement is

break

The following example demonstrates the use of the break statement.

for i in range(10): 
     if i==7:
         print("processing is enough..plz break") 
         break 
     print(i)

When the condition i==7 then the break statement will execute.

break-statement-one

The following example demonstrates the use of break statement

cart=[10,20,30,600,60,70] 
for item in cart:
     if item>500: 
         print("To place this order insurence must be required") 
         break 
     print(item)

When the item cost is more than 500, then the break statement will execute and prints the print statement.

break-statement-two

Use of Immutability

Continue Statement

Resuming the previous condition after an interruption is called Continue.

In python, the continue statement is used to skip the current iteration and continue with the next iteration and the syntax for continue statement is

continue

The following example demonstrates continue statement

for i in range(10):
     if i%2==0: 
         continue 
     print(i)

In the above example, we have a condition that I %2==0 that means if the number is even then it is equal to 0 and the iteration will continue further.

If the result is not equal to zero then, python will skip that iteration and prints it as it is.

for example, if i=1 and1%2 is not equal to 0 then python prints as 1, the output is

continue-statement-one

The following cart application program demonstrates the use of the continue statement

cart=[10,20,500,700,50,60]
for item in cart:
     if item>=500:
          print("We cannot process this item :",item) 
          continue
          print(item)

In the above program, if any item required insurance then python will skip that item and continue with next item.

continue-statement-two

The following example demonstrates the continue statement by using List datatype.

l=[10,20,0,5,0,30] 
for x in l:
    if x ==0:
        print("Hey how we can divide with zero..just skipping") 
        continue 
        print("100/{} = {}".format(x,100//x))

The output should be like below:
100/10=10
100/20=5
Hey how we can divide with zero..just skipping
100/5=20
Hey how we can divide with zero..just skipping
100/30=3

But when we run the above code in eclipse we got the out as below

continue-statement-three

If we remove the print statement and make x==0 then the result is as below

l=[10,20,0,5,0,30] 
for x in l:
    if x ==0:
      ##print("Hey how we can divide with zero..just skipping") 
        continue 
        print("100/{} = {}".format(x,100//x))

Then we should get the result as below:
100/10=10
100/20=5
100/5=20
100/30=3

But when we execute it with eclipse, python won't print anything

continue-statement-four

Console on PyDev

Loops with else block

In most of the programming languages else block is restricted to use with loops, but Python allows to use else block with for loop.

The following example demonstrates the use else statement with loops

cart=[10,20,30,40,50] 
for item in cart: 
    if item>=500: 
        print("We cannot process this order") 
        break  
    print(item)
else: 
    print("Congrats ...all items processed successfully")

In the above program, the cart value is below 500 and hence the program will execute only the else block.

else-block-with-loops-one

And if the cart value is greater than 500, then the output is

cart=[10,20,30,40,600,700,50] 
for item in cart: 
    if item>=500: 
        print("We cannot process this order") 
        break  
    print('processing item:',item)
else: 
    print("Congrats ...all items processed successfully")

In the above program if the condition becomes true and hence break statement will come out of the loop and prints the print statement as below

else-block-with-loops-two

In the above program if we use continue statement instead of a break then else block is going execute with two conditions also.

cart=[10,20,30,40,50] 
for item in cart: 
    if item>=500: 
        print("We cannot process this order") 
        break  
    print('processing item:', item)
else: 
    print("Congrats ...all items processed successfully")

if item>=500 is false, then the output is

else-block-with-loops-three

cart=[10,20,30,40,600,700,50] 
for item in cart: 
    if item>=500: 
        print("We cannot process this order") 
        continue  
    print('processing item:',item)
else: 
    print("Congrats ...all items processed successfully")

If item>=500 is true, then the output is

else-block-with-loops-four

The differences between for loop and while loop

For loop While loop
for loop is always based on some sequence and collections. while loop is always based on some condition, as long as the condition is true then the while loop is going to be executed.

None Datatype

Pass Statement

The pass statement is used only for the syntactical purpose and it does not execute any commands and codes, The pass statement is a keyword, wherever empty block is required we will use the pass statement.

The pass statement is a null operation when the pass statement executes nothing will happen and it also acts as a placeholder.

The syntax for the pass statement is

pass

Following example demonstrate the use of pass statement

for letter in 'chercher.tech': 
   if letter == 't':
      pass
      print('This is pass block')
   print ('Current Letter :', letter)

print ("Good bye!")

When the condition is true then the python will execute the pass statement

pass-statement-one

The use of pass statement

Sometimes in the parent class, we have to declare a function with an empty body and child class responsible to provide a proper implementation to it. Such type of empty body we can define by using pass keyword. (It is something like abstract method in Java).

example:

from abc import *
class Loan (ABC):
    @abstractmethod
    def getInterestRate(self):
        pass
    
class HomeLoan(Loan):  
    def getInterestRate(self):
        return 8
    
class VehicleLoan(Loan):  
    def getInterestRate(self):
        return 11
h=HomeLoan()
print(h.getInterestRate())

v=VehicleLoan()
print(v.getInterestRate())

The output is :

pass-statement-two

Python Installation

Del statement

Delete is nothing but removes/erase something which you do not want to keep.

In Python, everything is an object, so the del keyword is used to delete an object, the del keyword is also to be used for deleting a variable, and lists.

The following example is to demonstrate the use of delete statement

Let us consider L1 is pointing to an object if s2=s1 and s3=s2 then s1, s2, and s3 are pointing to the same object. to confirm that if you print as a print(id(s1,s2,s3)) .

then all the three reference variables are pointing to the same object

s1= "Orange"
s2=s1
s3=s2
del s1
print(id(s2))
print(id(s3))

The output is

del-statement-one

And hence if I delete s1, we can still access s1 through s2 and s3 so we have to delete s2 and s3 to delete the object completely.

del-statement-two

The del keyword cannot be used to remove elements present inside the immutable objects

s="Monster"
 del s

The above works perfectly

del-statement-three

And if you try to delete the elements present in the string Monster, then python will throw a type error.

s="Monster"
del s[0]

del-statement-four

Python Introduction

Prime Numbers in python

A positive integer greater than 1 which has no other factors other than one and itself is called a prime number.

Ex:2,3,5,7 are the prime numbers, as they do not have any other factors.

The Following program to check whether the given number is prime or not

n=int(input('Enter any number:'))
if n<=1:
    print("It is not prime number")
else:
    is_prime=True
    for i in range(2,n):
        if n%i==0:
            is_prime=False
            break
if is_prime==True:
    print("It is prime number")  
else:
    print("It is not prime number")  

If the input is 2, then the output is

prime-number-one

If the given input is 8

prime-number-two

The next example is to generate prime numbers which are less than or equal to the given number

n=int(input('Enter n value:'))
n1=2
while n1<=n:
    is_prime=True
    for i in range(2,n1//2+1):
        if n1%i==0:
            is_prime=False
            break
    if is_prime==True: 
        print(n1)
    n1=n1+1

If the given value is 10, then the prime numbers which are less than 10 are

prime-number-three

If the given value is 100, then the prime numbers which are less than 10 are

n=int(input('Enter n value:'))
n1=2
while n1<=n:
    is_prime=True
    for i in range(2,n1//2+1):
        if n1%i==0:
            is_prime=False
            break
    if is_prime==True: 
        print(n1)
    n1=n1+1
The output is:
Enter n value:100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

The following example to generate first n prime numbers

n=int(input("Enter n value:"))
count=0
n1=2
while True:
    is_prime=True
    for i in range(2,n1//2+1):
        if n1%i==0:
            is_prime=False
            break
    if is_prime==True:
        print(n1)
        count=count+1
    if count==n:
        break

When I execute the above program and entered the given value as 5, the output should be 2, 3, 5, 7, 11. these are the first two prime numbers, but I got the output as below

prime-number-four