BCS 360 Chapter 3-Selection
BCS 360 Chapter 3-Selection
1 Introduction
Statements in a Python program are executed sequentially in the order in which they appear. However,
Python has selection structures that can be used to decide which statements to be executed when a particular
condition is satisfied and which statements should be ignored. The condition to be tested could be made
R
up of variables, literals, relation operators and logical operators. These conditions are often referred to as
boolean expression as they always evaluate to True or False.
Note 1. True and False are not strings (they are not contained in quotation marks). They are the only
values of type bool. See the code below that demonstrates how to show type of True and False and how we
U
can assign boolean values to a variable.
1 n = True #We can assign True or False to a variable, just as we do with other values
2 print(type(n)) #Lets see that value contained in n is of type bool
3 print(True)
4
5
6
7
8
9
print(False)
print(type(True))
print(type(False))
’’’ −−−−−−−−−−−−OUTPUT−−−−−−−−−−−−
<class ’bool’>
UL
10 True
11 False
G
12 <class ’bool’>
13 <class ’bool’>
14 −−−−−−−−−−−−−END−−−−−−−−−−−−−−−−’’’
AN
Definition 1. A boolean expression is an expression that can only evaluate to either True or False.
1.1 if statement
if statement checks a boolean expression (condition) and evaluate the subsequent block of code if the
condition is True and skips the subsequent block of code if the condition is False. if statement is used for a
unary selection (when there is only one branch). The general structure of if statement is
1 if condition:
2 block of code
.
Note 2. block of code could consist of one statement or several statements indented to the same level.
To get out of the body of if (block of code), we use backspace key and place statements on the same
level as if as shown in the code
1 if condition:
2 block of code
3 am out if i will execute whether condition is true or false
U
2 n = int(input(’Enter a number: ’))
3 if n % 2 == 0: #Do not forget : at end of condition. Do not use = instead of ==
4 print(n, ’ is Even’)
5 ’’’ −−−−−OUTPUT−−−−−−
6
7
8
Enter a number: 4
4 is Even
−−−−−−−−−END−−−−−−−−−’’’ UL
2. A program that will read an integer from the keyboard and check if the integer is odd and display it.
1 #Read a number and display it if it is even
2 n = int(input(’Enter a number: ’))
G
3 if n % 2 != 0:
4 print(n, ’ is Odd’)
5 ’’’ −−−−−OUTPUT−−−−−−
6 Enter a number: 5
AN
7 5 is Odd
8 −−−−−−−−−END−−−−−−−−−’’’
3. Write a program that will read year from the keyboard and check if it is a leap year (Leap year is
divisible by 400 or 4)
1 year = int(input(”Enter Year: ”))
2 if year % 400 == 0 or year % 4 == 0: #Notice how we use or to make a compound boolean expression
3 print(year, ’ is a leap year’ )
.
4. Write a program that will check your age, if it is below 18 (as most of you are), it displays, Cannot
DR
vote
1 if age < 18:
2 print(”Cannot vote”)
1 if condition:
2
3
4
else :
UL
block of code to execute if condition is True
Figure 3 shows the flowchart of if. . . else statement. if. . . else is used when there are two possibilities of the
G
. AN
DR
problem at hand. For instance, a number is even or odd, a year is leap or not leap, gender is male or female,
even at the end of this semester, you will either pass or fail this module.
Each of the statements inside the first block of statements is executed in sequence if the boolean expression
evaluates to True. Te entire first block of statements is skipped if the boolean expression evaluates to True,
and instead all the statements under the else clause are executed.
Lets look at examples above and insert the else clause for each of them
1. A program that will read an integer from the keyboard and check if the integer is even or odd and
display it. (To check if a number is even, divide the number by 2 and check the reminder. If the
R
2. Write a program that will read year from the keyboard as an integer and check if it is a leap or not
leap year and display an appropriate message (Leap year is divisible by 400 or 4)
1 year = int(input(”Enter Year: ”))
2 if year % 400 == 0 or year % 4 == 0: #Notice how we use or to make a compound boolean expression
U
3 print(year, ’ is a leap year’ )
4 else :
5 print(year, ’ is a not a leap year’ )
1
2
3
4
5
UL
3. We can use the and, != operator and not operator in the leap year example as shown in code below
year = int(input(”Enter Year: ”))
if not(year % 400 != 0 and year % 4 != 0): #Notice how we use and to make a compound boolean expression
print(year, ’ is a leap year’ )
else :
print(year, ’ is a not a leap year’ )
G
4. Lets ask a user to enter her name, gender and age. Display name, age and message You qualify for
this gym if the user is a female above 18 years or a male below 18 years. Display You do not qualify
for this gym if a user is a female below 18 years or a male above 18 years.
name = input(”Enter your Name: ”)
AN
1
2 gender = input(”Enter your gender: ”)
3 age = int(input(’Enter your age: ’ ))
4 if gender == ’Female’ and age >= 18 or gender == ’Male’ and age < 18:
5 print(name, ’you are ’ , end = ’’)
6 print(age, ’years old’ , end = ’’)
7 print( ’ You qualify for this gym’)
8 else :
9 print( ’You do not qualify for this gym’)
This code shows you how we can use logical operators to create compound boolean expression, how
.
to use relational operators and how to create a block of code with several statements.
DR
Note 3. Order of operations In terms of order of operations, and is done before or, so if you have a
complicated condition that contains both, you may need parentheses around the or condition. Think
of and as being like multiplication and or as being like addition.
2. If one is a student, check if he/she has registered, else, display an error saying you are not a student
R
7 if registered : #check if the student has registered
8 if paid: #check if the student has paid
9 if gender == ’Male’ or gender == ’male’:
10 print( ’Allocated a room in P Block’)
11 else :
12 print( ’Allocated a room in Q Block’)
else :
U
13
14 print( ’You have not paid required fee’ )
15 else :
16 print( ’You have not registered’ )
17 else :
18 print( ’You are not a UKZN student’)
UL
This code is so dummy but it shows the idea of nested if and if. . . else statements. Lets look at another
example
G
1. A program that will read a number from the keyboard and check if it is even or odd. If the number
is odd, the program check if it is less than or equal to 5. If it is less than 5, it checks if it is 3. If it is
3, it displays the number. If the number is even, it checks if it is less than 10. If the number is less
than 10, it checks if it is greater than 5. If the number is greater than 5, it checks if it is 8, if it is 8,
AN
display it.
1 n = int(input(’Enter a number: ’))
2 if n % 2 != 0:
3 if n <= 5: #this could be written as if n < 5 or n == 5:
4 if n == 3:
5 print( ’The number you entered is’, n)
6 else :
7 print( ’The number is not 3’)
8 else :
9 print( ’The number is greater than 5’)
.
10 else :
DR
11 if n < 10:
12 if n > 5:
13 if n == 8:
14 print( ’The number is’, n)
15 else :
16 print( ’The number is not 8’)
17 else :
18 print( ’The number is less than 5’)
19 else :
20 print( ’The number is 10 or greater than 10’)
2. Program that reads mark of a student from the user as an integer, assign grade A if mark if greater
or equal to 100, grade B if mark is between 70 and 80, grade C if mark is between 60 and 70, garde
R
12 grade = ’D’
13 else :
14 if n >= 0 and n < 50:
15 grade = ’F’
16 else :
17 grade = ’Y’
U
18 print( ’Mark =’, n, ’Grade =’, grade)
UL
There could exist a chain of conditions that need to be tested and some block of code to be executed if a
particular condition is true (just as the example given above). Python provides elif selection structure that
can be used to write such code without too much indentation.
6 block of code 3
7 .
8 .
9 .
10 elif condition n:
11 block of code n
12 else :
13 block of code to be executed if all conditions are false
Example
.
1. Program that reads mark of a student from the user as an integer, assign grade A if mark if greater
or equal to 100, grade B if mark is between 70 and 80, grade C if mark is between 60 and 70, garde
DR
D if mark is between 50 and 60 and grade F if marks is below 50. No student can get above 100 nor
below 0. The program displays students mark and grade before exiting.
1 n = int(input(’Enter a numner: ’))
2 if n >= 80 and n <= 100:
3 grade = ’A’
4 elif n >= 70 and n < 80:
5 grade = ’B’
6 elif n >= 60 and n < 70:
7 grade = ’C’
8 elif n >= 50 and n < 60:
9 grade = ’D’
10 elif n >= 0 and n < 50:
11 grade = ’F’
Notice how this code is compact with less indentation compared to same example using nested if. . . else
Definition 2. A dangling else is an else statement that does not have a matching if statement.
R
See example below
1 age = 10
2 if age <= 18:
3 print( ’You are underage’)
4 else :
if age >= 18 and age <= 35:
U
5
6 print( ’You are a youth’)
7 else :
8 print( ’You are an adult’)
9
10
11
12
13
’’’ −−−−−−−−−OUTPUT−−−−−−−−−−−−−
else :
UL
Syntax Error: invalid syntax: <string>, line 7, pos 4
’’’
From this code, you can see that the if on line 2 has 2 else statements, one at line 4 and the other at line 7.
The else at line 7 is called a dangling else.
G
Note: The if at line 5 has no an else statement and it is syntactically correct. If it had an else state-
ment, then the else statement would be on the same indentation level as the if at line 5. The else at line 4
and 7 are for the if at line 2 because they are at the same indentation level.
AN
Note 4. Remember we can have an if without else, but we cannot have an else without a matching if
The not operator can make expressions more difficult to understand, especially if it is used multiple times.
.
Try only to use the not operator where it makes sense to have it. Most people find it easier to read positive
statements than negative ones. Sometimes we can use the opposite relational operator to avoid using the
DR
We can distribute not operator using DeMorgan’s law which states that
Tutorial questions
1. Write a program that will read radius of a circle from the keyboard as an integer, the x and y
R
coordinates of the centre of a circle and x and y coordinates of a point and determine if the point is
within a circle or outside the circle. [3 Marks]
2. Write a program that will read length of a square, x and y coordinates of a point and find out if the
point lies within the square. [3 Marks]
U
3. Write a program that read length and width of a rectangle, x and y coordinates of a point and find if
the point lies within the rectangle. [3 Marks]
UL
4. Using elif, write a program that reads a student mark from the keyboard and award grade and comment
as per the table below. Display student mark, grade and comment.
Mark
90 – 100
Grade
A
Comment
Excellent
[3 Marks]
75 – 89 B Good
60 – 74 C Fair
G
50 – 59 D Poor
0 – 49 F Fail
AN
6. Write a program that reads three floating point numbers from the user, find and display the minimum
number. [3 Marks]
7. Write a program that reads three integers from the user, find and display the maximum number among
the three. [3 Marks]
8. The post office charges parcel-senders according to the weight of their parcel. For a parcel weighing
.
2 kilograms or less the charge is R125. For each kilogram or part of a kilogram above 2 there is an
additional charge of R55. Write a program which inputs the weight of a parcel and outputs the amount
DR
9. A bus company has the following charges for a tour. If a person buys less than 5 tickets they cost R
1 500 each, otherwise they cost R1250 each. Write a program which calculates a customers bill given
the number of tickets. [3 Marks]
10. Write a program which reads the co-ordinates of three points and determines whether or not they lie
on a straight line. [3 Marks]
11. A baby sitter charges R 25 an hour between 18:00 and 21:30 and R 35 an hour between 21:30 and
midnight. She will not sit before 18:00 or after midnight. Write a program which reads the times
at which she started and finished sitting and calculates how much she earned. Your program should
check for invalid starting and finishing times. [4 Marks]
Write a program which inputs the three marks and outputs either PASS or SUPP GRANTED or
FAIL.
13. Write a program that will be given the length of two sides of a right-angled triangle and it should
return the length of the hypotenuse. [2 Marks]
R
14. Write a program which, given the length of three sides of a triangle, will determine whether the triangle
is right-angled. [3 Marks]
15. Write a program that reads in three positive integers representing day, month and year and indicate
whether or not these form a legitimate date. [4 Marks]
U
UL
G
. AN
DR