In this ICS3U Grade 11 Computer Science lesson you will be learning to:
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
Type the following code into the Python Editor
a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
print(a==b)
Type the following code into the Python Editor
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:
Type the following code into the Python Editor
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
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
Type the following code into the Python Editor
x = int(input("Enter a number: "))
print(x >= 3 and x <= 10)
First, let’s assume that the number entered was a 7.
Next if the number 12 was entered instead
Finally if the number 2 was entered instead
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.
Type the following code into the Python Editor
x = 3
y = 3
z = 1
print(x>5 or y == 3 and not(z>2))
The first thing that happens is the comparisons:
The not takes precedence next and changes the last False to a True
The program is now going to compare
The and takes precedence next so True and True evaluates to True
Now the program is going to compare
This is going to evaluate to True
Watch a video of your teacher summarizing the learning content for this section
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
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
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")
When a = 7
When a = 4
For all other inputs
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")
When x = 5 and y = 1
When x = 8 and y = 1
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")
For input that is greater than or equal to 100 :
For input that is less than 100:
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))
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))
Watch a video of your teacher summarizing the learning content for this section
The code written in last two activities above have something in common. Both were an either or decision to be made.
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.
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.
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)
Let’s say the numbers entered were a = 5, b = 4, c = 3
Let’s say the numbers entered were a = 4, b = 5, c = 3
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
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")
Watch a video of your teacher summarizing the learning content for this section
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:
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.
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")
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")
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")
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")
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)
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
#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))