Sunday, October 25, 2020

Conditional Statements in Python

Python programs contains statements that are executed sequentially. Let us understand the usage of conditional statements using an example: Allow booking of tickets to a show only when booked ticket count is less than the seating capacity available for the show. When seating capacity is filled completely display a message "No more Booking allowed". One such conditional statement in python is if.
Now let us write a program to do this:

Source code can be downloaded from GitHub
import sys
'''
    Program to demonstrate conditional statements in python
    Conditional statements in python if else
'''

def BookTickets():
    '''
        Reads Seating  Capacity and ticket Count as command
        line arguments.
        Using if and else condition to control the program flow
    '''
    try:
        SeatingCapacity = int(sys.argv[1])
        TicketCount = int(sys.argv[2])
        if ((SeatingCapacity - TicketCount) >= 0 ):
            print('Seats Available for Booking.. ', SeatingCapacity)
        else:
            print('No More Booking Allowed')
        
    except Exception as error:
        print(error)
    

if (len(sys.argv) < 3):
    print('Program Takes 2 arguments Seating Capacity and Ticket Count')
    exit(0)

BookTickets()



elif clause in python

In the above program we have used if else that is execute statements in if block on expression becoming true or statements in else block are executed. Always the control flow is either if or else. Now to add more control flow in the program we can use elif block.

Source code can be downloaded from GitHub

import sys

x = sys.argv[1]

if (x == 0):
    print('Ground floor')
if (x == 1):
    print("1st floor")
elif (x == 2):
    print ("2nd floor")
elif (x == 3):
    print ("3rd floor")
elif (x == 4):
    print ("4th floor")
elif (x == 5):
    print ("5th floor")
else:
    print ('Roof Top reached' )
  

Here we determine the floor in the building that we are currently based on value of x that is passed as an argument to the program.
Any value that is greater than 5 is passed always executes the else block determining roof top is reached.
Execute the code in elif block when all conditions above the elif are not satisfied. 

No comments:

Post a Comment

Operations on Python Dictionaries