ICS3U Python Selection Structures

ICS3U Learning Goals

In this ICS3U Grade 11 Computer Science lesson you will be learning to:

  • Understand boolean variables that represent True or False values
  • Write if – else statements using simple and compound comparison statements

Boolean Variables and Comparisons in Python

Now that you know how to store and manipulate data in a computer program, its time to start understanding how computers can use that data to make decisions.  Logic in python is controlled by boolean variables and comparison statements

Boolean variables can only take two values: True / False

				
					x = True
y = False
				
			

Notice that the True and False start with an upper case letter.  That is important, and if you write them differently you will generate an error.

The results of a comparison will act just like any other piece of data.  It can be stored in a variable, or used in other structures and functions

Comparisons for Equality and Inequality

In python we can test if variables are equal to each other using == and if they are not equal to each other using the != operator

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

  • Enter 2 numbers that are equal, and enter 2 numbers that are not equal.
  • Check to see if the output makes sense based on what you entered
				
					a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
print(a==b)
				
			

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

  • Enter 2 numbers that are equal, and enter 2 numbers that are not equal.
  • Check to see if the output makes sense based on what you entered
				
					a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
comparisonResult = a!=b
print(comparisonResult)
				
			

Comparisons for Greater Than or Less Than

Along with tests for equality, you can test for inequalities as well:

  • Greater than >
  • Greater than or equal to >=
  • Less than <
  • Less than or equal to <=

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

  • Run the program several times with several different values
  • Check to see if the output makes sense based on what you entered
				
					a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(a,"is greater than", b,"", a>b)
print(a,"is greater than or equal to", b,"", a>=b)
print(a,"is less than", b, "",a < b)
print(a,"is less than or equal to", b,"", a <= b)
				
			

Compound Comparisons

You can combine comparisons together to create more complex logic statements

  • and – only when both comparisons are True will this compound comparison evaluate to True
  • or – when either or both comparisons are True will this compound comparison evaluate to True
  • not – makes the comparison opposite to what it would normally evaluate to

In the table below, consider A and B to be comparisons that will evaluate to True or False

A B A and B A or B not A
False False False False True
False True False True True
True False False True False
True True True True False

There is an order of precedence to how these expressions are executed, just like in BEDMAS

The simple comparison operators precede the compound operators then not precedes and which precedes or

ICS3U Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

  • Run the code several times with values less than 3
  • Run the code several times with values between 3 and 10
  • Run the code several times with values larger than 10
  • What do you think this code does?
				
					x = int(input("Enter a number: "))
print(x >= 3 and x <= 10)

				
			

First, let’s assume that the number entered was a 7. 

  • The two comparisons are executed first and both evaluate to True.
  • So now you have a comparison of True and True
  • That comparison will evaluate to True

Next if the number 12 was entered instead

  • The first comparison evaluates to True, but the second comparison evaluates to False
  • So now you have a comparison of True and False
  • That will evaluate to False

Finally if the number 2 was entered instead

  • The first comparison evaluates to False, but the second comparison evaluates to True
  • So now you have a comparison of False and True
  • That will evaluate to False

This code will create a comparison that checks if a number entered from the keyboard is between 3 and 10 inclusive (3≤x≤10).  It should be fairly easy to see how to modify the code to make one or both of the end points exclusive.

ICS3U Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

  • Predict the value of the output before running the program
  • Check if you were correct
  • Find different values for the variable that will reverse the final output
				
					x = 3
y = 3
z = 1
print(x>5 or y == 3 and not(z>2))

				
			

The first thing that happens is the comparisons:

  • x>5 evaluates to False
  • y == 3 evaluates to True
  • z>2 evaluates to False

The not takes precedence next and changes the last False to a True

The program is now going to compare

  • False or True and True

The and takes precedence next so True and True evaluates to True

Now the program is going to compare 

  • False or True

This is going to evaluate to True

Video Summary

Watch a video of your teacher summarizing the learning content for this section

if Statements in Python

Important Facts to Remember

So far you have only written small pieces of code where each statement is executed one after the other in the order they are written.  However, there are times when you would like to change the way your code behaves based on a decision.

This is known as a selection structure

  • A selection structure is implemented using an if statement
  • If the answer to a comparison is true, then a certain block of code will be executed
  • If the answer to the comparison is false, then that certain block of code will not be executed.

Basically, an if statement asks the question: “Should I execute this group of statements once?”

The structure of the if statement is as follows:

				
					if comparison :

				
			

Any code that you want to be part of the if statement, MUST be indented once.  You can have as many statements as you want inside the if statement.  When the if is finished, the program continues with the non indented code underneath the if.  If the comparison was false, then the entire indented code is skipped

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

				
					a = int(input("Enter a number: "))

if a == 7:
    print("You entered my favourite number")
    
if a == 4:
    print("You entered my least favourite number")
				
			
  • Run the program with an input of 7
  • Run the program with an input of 4
  • Run the program with any other input

When a = 7

  • The comparison in the first if statement will evaluate to True
  • The program will print “You entered my favourite number”
  • The comparison in the second if statement will evaluate to False, so its code is not executed
  • Since there is no code below that the program is finished

When a = 4

  • The comparison in the first if statement will evaluate to False, so the indented code will not execute
  • The comparison in the second if statement will evaluate to True
  • The program will print “You entered my least favourite number” 
  • There are no more instructions after that so the program ends

For all other inputs

  • Both comparisons in the if statements are False, so both those print statements are skipped
  • The program ends without printing anything to the screen

 

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

				
					x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

if y > 3 or x <= 6:
    print("Winner Winner Chicken Dinner")
    
print("End")
    


				
			
  • Predict what the program will output if you enter x = 5 and y = 1
  • Predict what the program will output if you enter x = 8 and y = 1
  • Run your program to test if you were correct

When x = 5 and y = 1

  • y > 3 = False
  • x <=6 = True
  • False or True = True
  • Since the comparison in the if statement is True, the code in the if statement will execute so the program will print both “Winner Winner Chicken Dinner” and “End”

When x = 8 and y = 1

  • y > 3 = False
  • x <=6 = False
  • False or False = False
  • Since the comparison in the if statement is False, the code in the if statement will not execute so the program will only print “End”

Interactive Learning Activity - Grade 11 Computer Science

Type the following code into the Python Editor 

				
					a = int(input("Enter a Number: "))

if a>=100:
	print("Wow that is a big number")

if a < 100:
	print("Ohhh that is not a big number")

print("Program finished")

				
			
  • Run the code several times with values greater than 100
  • Run the code several times with values smaller than 100
  • Run the code by entering exactly 100
  • Check to see if the output makes sense based on what you entered

For input that is greater than or equal to 100 :

  • The code inside the first if statement is executed because the comparison evaluates to True
  • The program prints “Wow that is a big number”
  • The code inside the second if statement is not executed because the comparison evaluates to False
  • The final line of code is executed and the program prints “Program Finished”

For input that is less than 100:

  • The code inside the first if statement is not executed because the comparison evaluates to False
  • The code inside the second if statement is executed because the comparison evaluates to False
  • The program prints “Ohhh that is not a big number”
  • The final line of code is executed and the program prints “Program Finished”

Interactive Learning Activity - Grade 11 Computer Science

Let’s say you wanted to write a program that lets you save the tax on a purchase if you buy at least 5 of an item.  

Type the following code into the Python Editor.  It is only partially complete.

				
					numItems = int(input("Enter how many items: "))
costOfItem = float(input("How much does your item cost: "))

if __________:
	print("You will have to pay tax on that")
	total = ____________

if __________:
	print("No tax on that")
	total = ____________

print("Your items cost: $", round(total,2))
				
			
  • Fill in the blanks to make the program function as expected
  • Pick any number you want for the cost of an item when running the program
  • Run the code several times with values greater than 5 for the number of items
  • Run the code several times with values smaller than 5 for the number of items
  • Run the code by entering exactly 5 for the number of items
  • Check to see if the output makes sense based on what you entered.  Use your regular calculator to verify or check with my output

				
					numItems = int(input("Enter how many items: "))
costOfItem = float(input("How much does your item cost: "))

if numItems < 5:
	print("You will have to pay tax on that")
	total = (numItems * costOfItem)*1.13

if numItems >= 5:
	print("No tax on that")
	total = numItems * costOfItem

print("Your items cost: $", round(total,2))
				
			

Video Summary

Watch a video of your teacher summarizing the learning content for this section

if else Statements in Python

The code written in last two activities above have something in common. Both were an either or decision to be made. 

  • One had an if statement for ≥100 and <100
  • The other had an if statement for <5 and ≥5

It was guaranteed that one of the if statements would be executed no matter what the user entered. 

When you have to code an either or decision, it is common to use the if-else structure to accomplish the task instead of using two if statements

If True then do one thing, if False then do another.  

ICS3U if else python flow chart

Here are the two examples from the previous section written with if-else structures

				
					a = int(input("Enter a Number: "))

if a>=100:
	print("Wow that is a big number")

else:
	print("Ohhh that is not a big number")

print("Program finished")

				
			
				
					numItems = int(input("Enter how many items: "))
costOfItem = float(input("How much does your item cost: "))

if numItems < 5:
	print("You will have to pay tax on that")
	total = (numItems * costOfItem)*1.13

else:
	print("No tax on that")
	total = numItems * costOfItem

print("Your items cost: $", round(total,2))

				
			

You can also create a structure with if – else statements inside other if – else statements.  These are called nested selection structures.

Interactive Learning Activity - Grade 11 Computer Science

Let’s say you wanted to write a program that finds the largest of 3 numbers that entered from the keyboard

Type the following code into the Python Editor.

				
					a = int(input("Enter a number: "))
b = int(input("Enter a number: "))
c = int(input("Enter a number: "))

if a>=b:
	if a>=c:
		biggest = a
	else:
		biggest = c
else:
	if b>=c:
		biggest = b
	else:
		biggest = c

print("Biggest =",biggest)
				
			
  • Enter distinct values with a as the largest
  • Enter distinct values with b as the largest
  • Enter distinct values with c as the largest
  • What happens if you have some numbers that are equal?

Let’s say the numbers entered were a = 5, b = 4, c = 3

  • a≥b evaluates to True, so the code inside the outer if section will execute
  • Now the comparison a>=c will produce a True, so the code inside it will store the value of a (5) in the variable biggest
  • The inner else is skipped because a≥c was True
  • The outer else is skipped as well because the a≥b comparison evaluated to True earlier
  • The program then prints “Biggest = 5”

Let’s say the numbers entered were a = 4, b = 5, c = 3

  • a≥b evaluates to False, so the code inside the outer if section will not execute
  • Now the code in the else will start with the  comparison b≥c will produce a True, so the code inside it will store the value of b (5) in the variable biggest
  • The inner else is skipped because b≥c was True
  • The program then prints “Biggest = 5”

You can use the same logic to predict the other possibilities

You can even chain a bunch of if else statements together to form a program flow as follows.  Notice the use of the elif statement

ICS3U elif structure in python

A good example of when to use this structure is when the program is creating a menu for the user to make a choice from

				
					print("Enter 1 for option 1")
print("Enter 2 for option 2")
print("Enter 3 for option 3")

choice = int(input("Make your choice: "))

if choice == 1:
	print("Doing Option 1")
elif choice == 2:
	print("Doing Option 2")
elif choice == 3:
	print("Doing Option 3")
else:
	print("Invalid choice")
				
			

Video Summary

Watch a video of your teacher summarizing the learning content for this section

ICS3U Coding Questions

Try to code the following ICS3U questions using an IDE of your choice (Spyder, IDLE, Pycharm, etc).  You will save those files on your computer for future reference. 

Each question has:

  • A video of your teacher live coding and explaining the solution
  • The final code used in the video.

Try your best to solve the problems yourself without looking at the solutions.

Make sure you test your programs with multiple different inputs to ensure it is functioning properly.

ICS3U Practice Question

Name Your File:  “ICS3Udriving.py” 

Write a program that asks the user to enter their age.  Print out a statement if they are able to drive or not.  

				
					age = int(input("Enter your age"))

if age >= 16:
    print("You can drive")
else:
    print("You can't drive")
				
			

ICS3U Practice Question

Name Your File:  “ICS3UvolumeChoice.py” 

Write a program that calculates the volume of a 3D shape chosen by the user.  Give the user a choice between a Rectangular Prism, Cylinder, Sphere.  You will need to research the correct formulas if you can’t remember from your previous Math courses.

				
					#Display the menu

print("Volume Calculator")
print("1. Rectangular Prism")
print("2. Cylinder")
print("3. Sphere")

choice = int(input("Make your choice: "))

#Make calculations for each shape

if choice == 1:
    
    l = int(input("Enter the length: "))
    w = int(input("Enter the width: "))
    h = int(input("Enter the height: "))
    
    volume = l*w*h
    print("Volume = ", round(volume,3))
    
elif choice == 2:
    
    r = int(input("Enter the radius of the base:"))
    h = int(input("Enter the height: "))
    
    volume = (3.14*r**2) * h
    print("Volume = ", round(volume,3))
    
elif choice == 3:
    
    r = int(input("Enter the radius of the sphere:"))
    
    volume = 4/3*3.14*r**3
    print("Volume = ", round(volume,3))

else:
    
    print("you didn't make a valid choice")
				
			

ICS3U Practice Question

Name Your File:  “ICS3Uvoting.py” 

You can vote if you are 18 years and a citizen of the country. Write a program that ask the user their age and if they are a citizen and displays if they can vote or not

				
					#User input
age = int(input("Enter your age: "))
citizen = input("Citizen: yes or no: ")

#Determine if they can vote
if age >= 18 and citizen == "yes":
    print("You are allowed to vote")
else:
    print("You are not allowed to vote")

				
			

ICS3U Practice Question

Name Your File:  “ICS3UageSelection.py” 

Write a program that asks for the user’s age. If the user is under 9, output, “You are a young child”. For 9 to 17, output, “You are a child”. From 18 to 65, “You are an adult”. Over 65, “You are a senior”.

				
					age = int(input("Enter your age: "))

if age >= 0 and age < 9:
    print("You are a young child")
elif age >= 9 and age <=17:
    print("You are a child")
elif age >= 18 and age < 65:
    print("You are an adult")
elif age > 65:
    print("You are a senior")
else:
    print("Not a valid age")

				
			

ICS3U Practice Question

Name Your File:  “ICS3UcarSeat.py” 

Use the information on this webpage to write a program to help parents decide what car seat they should use. Pick your province.

https://www.babycenter.ca/a25019253/canadian-car-seat-laws-by-province-and-territory

				
					weight = int(input("Enter childs weight (kg): "))
age = int(input("Enter the childs age (years): "))
height = int(input("Enter the childs height (cm): " ))
    
if weight > 36 or height > 145 or age > 8:
    carSeat = "None Needed"
elif weight > 9 and weight <= 18:
    carSeat = "Forward Facing"
elif weight > 0 and weight < 9:
    carSeat = "Rear Facing"
else:
    carSeat = "Booster"
   
print("\nCar seat needed:")
print(carSeat)
				
			

ICS3U Practice Question

Name Your File:  “ICS3UcellPlan.py” 

Write a program that calculates the cost of a cell phone plan. The user will enter the following monthly amounts

Daytime voice minutes, Evening Voice Minutes, Weeked Voice Minutes, gB of data Used

The cost of the plan is as follows

  • 100 free day time minutes and then 25 cents per minute after that
  • 15 cents per evening minute
  • 20 cents per weekend minute to a maximum of 15 dollars
  • 30 dollars for 4gB and then 1.5 dollars per gB after that

				
					#User input
day = int(input("Enter daytime minutes: "))
evening = int(input("Enter evening minutes: "))
weekend = int(input("Enter weekend minutes: "))
data = int(input("Enter gB used: "))

#Calculate day cost
dayCost = 0
if day >= 100:
    dayCost = (day - 100)*0.25
    
#Calculate evening cost
eveningCost = evening * 0.15

#Calculate weekend cost
weekendCost = weekend * 0.2
if weekendCost > 15:
    weekendCost = 15

#Calculate data cost
dataCost = 30
if data >= 4:
    dataCost = dataCost + (data-4)*1.5

#Find the total cost
totalCost = dayCost + eveningCost + weekendCost + dataCost

#Display the results
print("The cost of your usage is: $",round(totalCost,2))

				
			

Return to ICS3U1 Main Page