Control Statements
Control statements enable us to specify the order in which the various statements in a
program are to be executed.
The control statements fall into three categories depending on how they affect the order in
which the statements are executed.
Selection statements Iterative statements Transfer statements
If while break
if- else for continue
if – elif - else pass
return
The if statement
The if statement is a selection control statement, it selects the appropriate set of
instructions to execute based on the value of a given Boolean expression .
In python-speak a block of code that is a sequence of one or more statements is called a
suite.
Indentation in python:
One fairly unique aspect of python is that the amount of indentation of each program line is
significant. In Python indentation is used to associate and group statements
A sequence of one or more statements with same level of indentation is called a suite.
Simple if statement
___________________________________
if Boolean expression :
if_suite
statement-x ----------------------------- immediate next statement after the if structure
______________________________
If the Boolean expression evaluates to True , the if_suite gets executed and then the next
statement after the simple if structure i.e statement-x gets executed .
If the Boolean expression evaluates to False , the if suite is skipped off and the control goes
to the next statement after the simple if structure
An Example of simple if statement
#program to calculate discount
#A discount 16 % is offered is to the customers on purchases value Rs 10,000 or more
discount, discount_amount = 0.0 , 0.0
purchases = float ( input ( ‘ Enter the value of purchases : Rs’ ) )
if purchases >= 10000 : # A header in python is a specific keyword followed by a :
discount , discount_amount=16, (purchases*discount/100)
print ( ‘ Discount =%.2f %%’ %(discount) )
print ( ‘ DiscountAmount =%.2f %%’ %(discount_amount) )
total_bill = purchases - discount_amount
print ( “ TotalBill = Rs %.2f ’ %( total_bill ))
Test Cases
Test Case-1 : Enter the value of purchases: RS 12500
Discount = 16 %
DiscountAmount = Rs. 2000.00
TotalBill= Rs. 10500.00
Test Case-2 : Enter the value of purchases : Rs 8000
TotalBill = Rs 8000.00
The if..else statement
The syntax of if..else statement is as follows
_________________________________________________________________
if boolean_expression :
if_suite
else:
else_suite
Statement-x #immediate next statement that follows the if..else construct
__________________________________________________________________-
The if..else statement will execute of statements if the boolean_expression is true or
another group of statements if the boolean_expression is false.
In both the cases the control is transferred subsequently to the next statement that follows
the if else construct
An example of if..else statement
#program to check whether a person is eligible for voting or not
age = int ( input ( ‘ Enter the age: ’ )
if age >= 18:
print ( ‘ Eligible for voting ’ )
else:
print ( ‘ Not eligible for voting ’ )
Test Cases
Test Case -1 : Enter the age: 24
Eligible for voting
Test Case-2: Enter the age: 13
Not eligible for voting
The nested if..else statement
In order to select one set of statements between two different sets of statements one if is
required
There are often times when selection among more than two sets of statements is needed,
for such situations if statements can be nested, resulting in multi-way selection.
The if..else statements must be nested to achieve multi-way selection.
If we write an entire if..else construct within either in the if_suite or in the else_suite , the
resulting structure is called nested if..else
if boolean_expression 1:
#outer if_sute
if boolean_ expression 2 :
if_suite
else:
else_suite
#outer if_suite
else:
#outer else_suite
if boolean_expression 3:
if_suite
else:
else_suite
#outer else_suite
#program to calculate profit or loss
cp = float ( input ( ‘ Enter cost price: ‘ )
sp = float ( input ( ‘ Enter selling price: ‘ )
if sp == cp :
print( ‘ No Profit , No Loss ‘ )
else:
if sp > cp :
profit = sp - cp
print( ‘ Profit=Rs %,2f ‘ % profit )
else:
loss = cp - sp
print( ‘ Loss=Rs%.2f ‘, loss )
Test Cases
Test case 1 : Enter cost price: Rs 300
Enter selling price: Rs 500
Profit=Rs 200.00
Test Case 2: Enter cost price: Rs 500
Enter selling price : Rs 200
Loss=Rs 300
Test Case 3: Enter cost price: Rs 700
Enter selling price : Rs 700
No profit, No loss
short circuit operators ( and , or ):
============================
short circuit operators allow two or more boolean_expressions to be combined in an if
statement
#program to check three numbers are equal or not
if a==b: 2 2 5
if a==c:
print('Three number are equal')
else:
print('Three numbers are not equal')
else:
print('Three number are not equal')
APPROACH II
-------------------
#program to check three numbers are equal or not
if a==b and a==c:
print('Three numbers are equal')
else:
print('Three numbers are not equal')
#program to check pass or fail
if m1 < 35:
print('Fail')
else:
if m2<35:
print('Fail')
else:
if m3<35:
print('Fail')
else:
print('Pass')
APPORACH II
--------------------
#program to check pass or fail
if m1<35 or m2<35 or m3<35:
print('Fail')
else:
print('Pass')
Programming Exercise
Write a python program to calculate grade of a student
A student must obtain at least 35 marks in each subject other wise he/she is declared as a
fail and no grade is assigned. Grade is calculated to those students who has secured
minimum 35 marks in each subject
Average Grade
>=60 A
>=50 and <60 B
>=40 and <50 C
>40 D
#program to calculate grade of a student
m1, m2 , m3 = [ int ( x ) for x in input ( ‘ Enter marks in three subjects:’.split( ) ]
total, avg, grade =0, 0.0, ‘ ‘
if m1 < 35 or m2 < 35 or m3 <35 :
print (" fail ")
else:
total = m1 + m2 + m3
avg = total / 3
if avg >= 60 :
grade= ’ A ’
else:
if avg >= 50:
grade = ’ B ’
else:
if avg >= 40:
grade = ’ C ’
else:
grade = ’ D ’
print( ‘ Total=%d \n Grade = %s ’ % (total,grade) )
if ..else statements must be nested to achieve multi-way selection.
Indenting is important in nested statements, a long series of nested if..else statements can
become too long to be displayed on the computer screen without horizontal scrolling. Also
long statements tend to wrap around when printed on paper, making the code even more
difficult to read.
elif clause can be write a multi-way selection .
elif clause is a way of rearranging the else with the if that follows it.
The Cascading elif clause
if boolean_expression1:
Suite1
elif boolean_expression2:
Suite2
elif boolean_expression3:
Suite3
............................
elif boolean_expressionN:
SuiteN
else:
else_suite
statement-x #The immediate next statement that follows the if-elif-else structure
The boolean_expressions are evaluated from the top to the bottom.
If any one of the boolean_expressions is found to be true, then the suite associated with it
is executed and the rest of the structure is ignored and the control is transferred to the next
statement that follows the if-elif-else structure .
If none of the boolen_expressions are true, the last else clause and the suite associated
with the else is executed.
#program to calculate grade of a student
m1, m2 , m3 = [ int ( x ) for x in input ( ‘ Enter marks in three subjects:’.split( ) ]
total, avg, grade =0, 0.0, ‘ ‘
if m1 < 35 or m2 < 35 or m3 <35 :
print (" fail ")
else:
total = m1 + m2 + m3
avg = total / 3
if avg >= 60 :
grade=’A’
elif avg >= 50:
grade=’B’
elif avg >= 40:
grade=’C’)
else:
grade=’D’
print( ‘ Total = %d \n Grade=%s ’ % (total , grade))
Test Cases
Test Case-1: Enter marks in three subjects : 45 48 38
Total=161
Grade=C
Test Case-2: Enter marks in three subjects 65 68 72
Total=205
Grade=A
Test Case-3 : Enter marks in three subjects 12 23 34
Fail
Programming Exercise
Calculate late fine
Days Fine per day
1-5 Rs 1.00
6 – 10 Rs 2.00
11 – 30 Rs 5.00
> 30 Member ship will be cancelled
# program to calculate late fine
days=int(input ("Enter number of days late:"))
late_fine=0
if days <= 5:
late_fine = days * 1
print("Latefine = Rs ",late_fine)
else:
if days<= 10 :
late_fine = 5 * 1 + ( days - 5 ) * 2
print("Latefine = Rs ",late_fine)
else :
if days <= 30:
late_fine = 5 * 1 + 5 * 2 + ( days - 10 ) * 5
print("Latefine = Rs ",late_fine)
else:
print("Membership has been cancelled”)
# program to calculate late fine
days=int(input ("Enter number of days late:"))
late_fine=0
if days <= 5:
late_fine = days * 1
print("Latefine = Rs ",late_fine)
elif days<= 10 :
late_fine = 5 * 1 + ( days - 5 ) * 2
print("Latefine = Rs ",late_fine)
elif days <= 30:
late_fine = 5 * 1 + 5 * 2 + ( days - 10 ) * 5
print("Latefine = Rs ",late_fine)
else:
print("Membership has been cancelled”)
Programming Exercise
Calculating share broker commission
When stocks are sold or purchased through a broker .the broker commission is often
computed using a sliding scale that depends upon the value of the stocks traded.
A broker charges the amounts shown in the following table
Transaction Commission rate
Under $ 2500 $ 30 + 1.7 %
$ 2500 - $ 6250 $ 56 + 0.66 %
$ 6250 - $ 20000 $ 76 + 0.34 %
$ 20000 - $ 50000 $ 100 + 0.22 %
$ 50000 - $ 500000 $ 155 + 0.11 %
Over $ 500000 $ 225 + 0.09 %
#calculate a share broker commission
value= float ( input ( ‘ Enter the value of trade: ‘ )
comm = 0
if value < 2500:
comm = 30 + 0.017 * value
else:
if value < 6250:
comm = 56 + 0.0066 * value
else:
if value < 20000:
comm = 76 + 0.0034 * value
else:
if value < 50000:
comm = 100 + 0.0022 * value
else:
if value < 500000:
comm = 155 + 0.0011 * value
else:
comm = 255 + 0.0009 * value
print ( ‘ \n commission = $%.2f " , comm )
Test Case
Test Case-1 : Enter the value of trade : $30000
Commission : $166.00
The commission can be calculated using the cascading elif as follows
value=float ( input (‘ Enter value: ’ )
if value<2500:
comm = 30 + 0.017 * value
elif value< 6250:
comm = 56 + 0.0066 * value
elif value< 20000:
comm = 76 + 0.0034 * value
elif value< 50000:
comm = 100 + 0.0022 * value
elif value< 500000:
comm = 155 + 0.0011 * value
else:
comm = 255 + 0.0009 * value
print ( “ commission = $%.2f ‘’,%comm )
The cascaded if statement could have been written this way
if value < 2500:
comm = 30 + 0.017 * value
elif value >= 2500 and value < 6250:
comm = 56 + 0.0066 * value
elif value >= 6250 and value < 20000:
comm = 76 + 0.0034 * value
- - - - - - - - - - - - - - - - - - - - -- - - - - -- - - - - - - - - - - - - - - - - - - - - -
Although the program will still work, the added conditions are not necessary. for example,
the first if clause tests whether the value is less than 2500 and if so, computes the
commission. When we reach the second if test ( value> =2500 and value < 6250 ) we know
that value can not be less than 2500 and there fore, must be greater than or equal to 2500.
The condition value >= 2500 will always be true. So there is no need in checking it.
#program to find next date of a given date
day,month,year=[int(x) for x in input('Enter the date :(dd/mm/yyyy) ').split('/')]
if month ==12:
if day==31:
day=1
month=1
year=year+1
else:
day=day+1
print('next date {} / {} / {}'.format(day,month,year))
elif month in [1,3,5,7,8,10]:
if day==31:
day=1
month=month+1
else:
day=day+1
print('next date {} / {} / {}'.format(day,month,year))
elif month in [4,6,9,11]:
if day==30:
day=1
month=month+1
else:
day=day+1
elif month==2:
if ( (year%4==0) and not (year%100==0) or (year%400==0) ):
if day==29:
day=1
month=month+1
else:
day=day+1
else:
if day==28:
day=1
month=month+1
else:
day=day+1
print('next date {} / {} / {}'.format(day,month,year))
else:
print('Invalid Date')
Test Cases
Test Case-1: Enter a date : 09/12/1996
Next date:10/12/1996
Test Case-2: Enter a date : 28/02/1996
Next date:29/02/1996
Test Case-3: Enter a date : 31/12/1996
Next date:01/01/1997
Test Case-4: Enter a date : 06/15/1996
Invalid date