In this ICS3U Grade 11 Computer Science lesson you will be learning to:
Computer software has the ability to repeat sets of code over and over and over again very quickly. This turns out to be very advantageous when solving particular types of computational problems. These programming structures are often called loops.
These structures work very much like if statements, but where an if statement only executes the code ONE time when the comparison is true, a loop will repeat the code inside it indefinitely while the comparison is true. Only when the comparison becomes false will the code inside a loop stop executing. In this lesson you will see various strategies that you can use to make the loop execute the correct number of times before stopping
Python contains two types of looping structures:
There are also generally 3 types of ways we would use those structures to solve problems
A while loop structure is much like an if statement, but you use the keyword while with a comparison, and all the code you want to repeat gets indented.
while comparison:
#Code to Repeat
In a counted while loop, we use a variable called a counter that changes each time the repeated code executes. That counter will eventually make the comparison false and the code will stop repeating. Its easy to design the comparison and the counter to make the code execute a predetermined amount of times.
Let’s say you wanted to create a program that prints “Hello” on the screen 10 times using a repetition structure. The flow of that program would look something like this:
To get an understanding of how exactly this code would accomplish our task, let’s TRACE through the values of the variables as the loop executes.
We can make a chart of what each important variable is doing step by step through the program.
You can see that each time through the loop, the value of the counter changes. That changing counter will make the comparison eventually become false and the code in the loop will stop executing.
Type the following code into the Python Editor
counter = 0
while counter < 10:
print("Hello")
counter = counter + 1
Let’s continue thinking about the program from before. We were able to get a piece of code to execute 10 times by starting a counter at 0, increasing the counter by 1 each time the loop executes, and using the comparison counter < 10.
There are really an infinite number of ways to change how that code was written and still get a piece of code to execute ten times
Type the following pieces of code into the Python Editor
Example 1:
counter = 1
while counter <= 10:
print("Hello")
counter = counter + 1
Example 2:
counter = 5
while counter < 15:
print("Hello")
counter = counter + 1
Example 3:
counter = 0
while counter < 20:
print("Hello")
counter = counter + 2
In all three examples, you can change:
So how do you know what to do? -> You don’t always. The problem you are solving dictates how the loop needs to be created. That requires some THINKING on your part. Most of the time there will be many different ways you can solve the problem.
In this example we want to calculate the area of 3 rectangles. The user gets to enter the length and the width of the rectangle.
The following code would accomplish the task but it would be an inefficient way to solve the problem
#First Rectangle
length1 = int(input("Enter the length: "))
width1 = int(input("Enter the width: "))
area1 = length1 * width1
print("The area is",area1)
#Second Rectangle
length2 = int(input("Enter the length: "))
width2 = int(input("Enter the width: "))
area2 = length2 * width2
print("The area is",area2)
#Third Rectangle
length3 = int(input("Enter the length: "))
width3 = int(input("Enter the width: "))
area3 = length3 * width3
print("The area is",area3)
If you are writing code that is repeating itself many times, then that is an indication that you should be using a loop to accomplish the task…. and this code appears to be doing the same thing over and over again.
#First Rectangle
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
#Second Rectangle
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
#Third Rectangle
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
You don’t actually need all of those variables, you could just reuse the length, width, and area variables. Once the program does the area calculation and prints the area calculation it won’t matter if the value of those variables are lost and changed in memory. There is no use keeping them in this program
Type the following code into the Python Editor. It is only partially complete.
counter = ___
while _____________:
#Rectangle Calculation (The stuff I want to repeat)
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
#Increase Loop Counter
counter = counter + _____
counter = 0
while counter < 3:
#Rectangle Calculation (The stuff I want to repeat)
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
#Increase Loop Counter
counter = counter + 1
#Ask the user for how many rectangles
numRectangles = int(input("Enter the number of rectangles you wish to calculate: "))
counter = 0
while counter < numRectangles:
#Rectangle Calculation (The stuff I want to repeat)
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length * width
print("The area is",area)
#Increase Loop Counter
counter = counter + 1
Sometimes you might want to use the counter variable to help solve the problem you have been given.
Let’s say you were asked to print all the even numbers between 0 and 30 to the screen.
Type the following code into the Python Editor and run the program
counter = 2
while counter <= 30:
print(counter)
counter = counter + 2
2 is the first even number in the range, so I started the counter at 2, but instead of increasing the counter by 1 each time, I increased it by 2, so it would print 2, 4, 6, 8, etc…
In the following program, we want to display and count how many numbers between 0 and 500 are divisible by 4
Type the following code into the Python Editor.
numDiv = 0
counter = 1
while counter <= 500:
if counter % 4 == 0:
print(counter, "is divisible by 4")
numDiv = numDiv + 1
counter = counter + 1
print("There were", numDiv, "values divisible by 4")
The variable numDiv is storing the total number of values between 0 and 500 that are divisible by 4
The program needs to check each value from 1 to 500 for divisibility, so in this case the loop counter is the value we are checking.
You don’t need to name the loop counter, “counter”. In this case it might make more sense to name counter, numToCheck, like in the following code
#Variable to store the total number of values divisible by 4
numDiv = 0
#Numbers from 1 to 500 need to be checked for divisibility
numToCheck = 1
while numToCheck <= 500:
#Check if the number is divisible by 4
if numToCheck % 4 == 0:
#Output number that is divisible to the screen
print(numToCheck, "is divisible by 4")
#Increase the total number of values divisible by 4
numDiv = numDiv + 1
#Move to the next number
numToCheck = numToCheck + 1
#Output the total
print("There were", numDiv, "values divisible by 4")
Here is the code that modifies the program to include a user defined range and divisibility number.
#Variable to store the total number of values divisible by 4
numDiv = 0
#Get info from the user
start = int(input("Enter starting value: "))
end = int(input("Enter ending value: "))
d = int(input("Check divisibility by: "))
#Numbers from start to end need to be checked for divisibility
numToCheck = start
while numToCheck <= end:
#Check if the number is divisible by d
if numToCheck % d == 0:
#Output number that is divisible to the screen
print(numToCheck, "is divisible by", d)
#Increase the total number of values divisible by d
numDiv = numDiv + 1
#Move to the next number
numToCheck = numToCheck + 1
#Output the total
print("There were", numDiv, "values divisible by", d)
Let’s say you wanted to create a program that adds up the numbers from 0 to 10
The flow of that program might look something like this
Here is the trace of that program as it executes
You can see how the variable sum is constantly being modified to increase each time through the loop. This is a really useful piece of code because it is easily modified to add up ANY value (like numbers entered from the keyboard)
Type the following code into the Python Editor
s = 0
counter = 0
while counter < 10:
s = s + counter
counter = counter + 1
print("The final sum is: ", s)
Watch a video of your teacher summarizing the learning content for this section
A for loop is another structure in python that is really good at counted loops. Its more compact to write, but perhaps a little less flexible than a while loop. The counter change ALWAYS occurs at the last step of the loop. There may be certain scenarios where you don’t want that to happen and need the counter to change at some other point.
Here is the general structure of a for loop that automatically counts up from start to end – 1 by 1 (The end value is exclusive and not included in the range. It is using a less than comparison, not less than or equal to). That might seem silly, but it will have its advantages when dealing with lists in the next unit
for counter in range(start,end):
#Code to Repeat
You can also make the counter increment by different values as well. That increment can be positive and negative values. That increment value CANNOT be a floating point number, it must be an integer
for counter in range(start,end,increment):
#Code to Repeat
You probably won’t see a lot of for loops in the rest of this lesson, but they will show up almost exclusively when dealing with lists later in the course
Here are some examples of for loops printing out their range with different increments
Type the following pieces of code into the Python Editor
Example 1:
for counter in range(1,10):
print(counter)
Example 2:
for counter in range(0,20,3):
print(counter, end = " ")
Example 3:
for counter in range (50,0,-1):
print(counter, end = " ")
Remember that you don’t have to use the variable name counter to represent the counter in the loop. Use what makes sense to you and the problem you are solving.
Traditionally the variable i is typically used to represent the counter variable in a loop. Even j and k as well if you have nested loops. (I don’t really know why, but its very common for math subscripts to use them as well)
i = 0
while i < 3 :
print ("Typing less can be better")
i = i + 1
for i in range(0,3):
print("Typing less can be better")
Conditional loops continuously executes until something happens when the program is executing to tell it to stop.
ICS3U Example 1 – Using a break statement with an infinite loop
A break statement causes the loop which is currently executing to stop immediately and go to the next sequence of code. Typically this would be used inside an if so you can create a comparison when you want the program to stop
This program will continuously ask the user to keep printing the word “Hi” to the screen
Type the following pieces of code into the Python Editor
#Infinite Loop
while True:
#Code to Repeat Forever
print("Hi")
#Give the user control when to stop
choice = input("\tDo you wish to continue (Y):")
if(choice != "Y"):
break
print("Loop Stopped")
The condition of the while loop will never change from True, so it will keep executing forever.
The if statement will stop the loop when anything other than an Uppercase Y is entered using the break statement.
When the Uppercase Y is entered it skips the break and starts the loop over
ICS3U Example 2 – Using a flag
Another way to accomplish the same task is shown below. It makes use of a boolean variable that will change to false when the correct condition is met. This is boolean variable is usually called a flag in programming.
continuing = True
while continuing:
#Code to repeat forever
print("Hi")
#Give the user control when to stop
choice = input("\tDo you wish to continue (Y):")
if(choice != "Y"):
continuing = False
print("Loop Stopped")
ICS3U Example 3 – Using a comparison
Finally, a third way of accomplishing this task is to use a comparison in the while statement. You just need to make sure the comparison evaluates to True the first time through the loop and eventually it will turn false when the user says he wants to quit
choice = "Y"
while choice == "Y":
#Code to repeat forever
print("Hi")
#Give the user control when to stop
choice = input("\tDo you wish to continue (Y):")
print("Loop Stopped")
Watch a video of your teacher summarizing the learning content for this section
Nested Repetitions are when you have loops inside other loops. What you need to remember is that an inner loop will always finish before starting the next iteration of the outer loop.
Suppose you wanted to create a program for a teacher that calculated a class of students individual averages for their assignments that she has stored as a paper copy in her teacher binder.
This would be an example that would need nested loops:
When coding these type of problems, you might find it easier to start with the inner loop code, and once that is working you “Loop the Loop”
Here would be the inner code for the above example. Let’s assume there are 4 assignments, so this piece of code will just calculate the average for 1 student
#total of the grades
total = 0
#Loop for 4 assignments
for assignment in range(1,5):
#Get assignment grade from keyboard
print("Enter Assignment",assignment,"mark:", end = "")
grade = int(input())
#Add up all the grades
total = total + grade
#Calculate the average
average = total / 4
#print the average
print("Average = ", round(average,2), "%")
Now you just have to think of how to make this code work for an entire class. Let’s assume there are 20 students in the class, so a simple counted loop that goes from 1 to 20 would work
#Loop for the number of students in the class (20 Students)
for student in range(1,21):
#Code that needs to repeat
You could now just copy the code for the inner loop into the code for the outer loop
#Loop for the number of students in the class (20 Students)
for student in range(1,21):
#Print to student # to help keep things organized
print("Student", student, ":")
#total of the grades
total = 0
#Loop for 4 assignments
for assignment in range(1,5):
#Get assignment grade from keyboard
print("Enter Assignment",assignment,"mark:", end = "")
grade = int(input())
#Add up all the grades
total = total + grade
#Calculate the average
average = total / 4
#print the average
print("Average = ", round(average,2), "%")
#Make a new line to help with readability
print("")
This program is going to have you draw a box with * on the screen. The user can control how many rows and how many columns to draw
Type the following pieces of code into the Python Editor
numRows = int(input("Rows: " ))
numColumns = int(input("Columns: "))
for row in range(0,numRows):
for col in range(0,numColumns):
print("*",end="")
print("")
Remember that the inner loop will execute completely first.
The inner loop has only 1 job and that is to draw a bunch of * all on the same line.
When the inner loop finishes there is a blank print statement which will put the cursor down to the next line.
That inner loop is then repeated for the correct number of rows that the user entered
Here is the code written as while loops instead of for loops
numRows = int(input("Rows: " ))
numColumns = int(input("Columns: "))
row = 0
while row < numRows:
col = 0
while col < numColumns:
print("*",end="")
col = col + 1
print("")
row = row + 1
This program will show how you can adjust how many times the inner loop executes based on the value of the counter on the outer loop.
Take the program that you just wrote, but instead of printing a full box, you print only a wedge (each row has one less * in it)
Type the following pieces of code into the Python Editor
wedgeSize = int(input("Wedge Size: "))
row = 0
while row < wedgeSize:
col = 0
while col < wedgeSize - row:
print("*",end="")
col = col + 1
print("")
row = row + 1
The program is basically the same as the full box, but you need to reduce the number of times that the inner loop executes. Look for a relationship between the row # and how many * need to get printed.
Here is the code for the reversed wedge
wedgeSize = int(input("Wedge Size: "))
row = wedgeSize
while row > 0:
col = 0
while col <= wedgeSize - row:
print("*",end="")
col = col + 1
print("")
row = row - 1
ICS3U Example – Hollow Box
You are not restricted to just an outer and one inner loop. There might be a bunch of loops inside the outer loop.
Consider this hollow box where the number of rows and number of columns drawn are determined by user input
If you were to write a program to print this box you might
numRows = int(input("Rows: " ))
numColumns = int(input("Columns: "))
#Draw the top line
col = 0
while(col < numColumns):
print("*", end="")
col = col + 1
print("")
#Draw the middle
row = 0
while(row < numRows-2):
#Print the first star
print("*", end = "")
#Print the spaces inbetween
col = 0
while(col < numColumns - 2):
print(" ", end = "")
col = col + 1
#print the last star
print("*")
row = row + 1
#Draw the bottom line
col = 0
while(col < numColumns):
print("*", end="")
col = col + 1
print("")
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: “ICS3UcountBetween.py”
Write a program that asks the user to enter two numbers and prints all the numbers in between on one line, separated by commas. Use a for loop and a while loop
#Input
start = int(input("Starting Number: "))
end = int(input("Ending Number: "))
#While Loop
print("\nUsing while:")
num = start
while num<=end:
print(num,end = ",")
num = num + 1
#For Loop
print("\nUsing for:")
for num in range(start,end+1):
print(num,end = ",")
Name Your File: “ICS3UrepeatTriangle.py”
Write a program that asks for the base and height of a right triangle and prints its perimeter, area, and 3 angles
Let the user pick how many triangles they want to enter before the program stops. Use a for loop for the solution
import math
#How many times to execute loop
numTriangles = int(input("How many triangles? "))
#loop
for i in range(1,numTriangles+1):
print("\nTriangle:", i)
#Inputs
base = int(input("Enter the base: "))
height = int(input("Enter the height: "))
#calculate area
area = 1/2*base*height
#calculate perimeter
hypotenuse = math.sqrt(base**2 + height**2)
perimeter = base + height + hypotenuse
#calculate angles
angle1 = math.degrees(math.atan(height/base))
angle2 = math.degrees(math.atan(base/height))
angle3 = 90
#Display answers
print("\nArea:", round(area,1))
print("Perimeter:", round(perimeter,1))
print("Angles: ", round(angle1,1), round(angle2,1), round(angle3,1))
Name Your File: “ICS3UmyAverage.py”
Write a program that generates 15 random numbers between 50 and 100. Display the numbers and the average
import random
print("The numbers are: ")
#Use a loop to add up all the numbers
total = 0
i = 1
while i<=15:
#Generate the numbers
num = random.randint(50,100)
print(num, end = " ")
#Calculate the sum
total = total + num
i = i + 1
#Calculate the average
average = total / 15
print("\nThe average of those numbers are:", round(average,1))
Name Your File: “ICS3UconditionalArea.py”
Write a program that generates a random number between 0 and 25 representing the radius of a circle. Use that number to print out the area. Have the program stop only when the area is larger than 1200
import random
#Loop forever
while True:
#Generate Random radius
r = random.randint(0,25)
#Calculate and print area
area = 3.14*r**2
print("A circle of radius",r," has an area of",area)
#Stop the loop
if area >= 1200:
break
Name Your File: “ICS3UcountPositive.py”
Write a program that asks the user to enter a number. End the program when the user enters a negative number. Count how many numbers the user entered. Tell the user the result (don’t include the negative that stopped the program)
#Running total of all postive numbers
count = 0
#Loop forever
while True:
#Get Value from keyboard
value = int(input("Enter a number: "))
#Check if positive and increase count or stop the loop
if value >= 0:
count = count + 1
else:
break
print("You entered",count," positive numbers")
Name Your File: “ICS3UuntilZero.py”
Write a program that displays random numbers between -50 and 50 until the number zero shows up. At the end of the program, display how many numbers were printed above/below zero, and the percentage of positive and negative numbers that showed up before that happened.
import random
#Counting variables for pos and neg #'s
countP = 0
countN = 0
#Loop until a zero and count
while True:
num = random.randint(-50,50)
print(num)
if num > 0:
countP = countP + 1
elif num < 0:
countN = countN + 1
else:
break
#Make Calculations
total = countP + countN
avgP = countP/total*100
avgN = countN/total*100
#Display answers
print("\nTotal Numbers:",total)
print("Positive:", round(avgP,1),"%")
print("Negative:", round(avgN,1),"%")
Name Your File: “ICS3UcountedWedge.py”
Write a program that draws a counted wedge on the screen. The user gets to control the size of the wedge
size = int(input("Enter size: "))
#Count Up Wedge
row = 0
while row <=size:
col = 1
while col <= size - row:
print(col, end = " ")
col = col + 1
print("")
row = row + 1
#Count Down Wedge
row = 0
while row <=size:
col = size
while col > row:
print(col, end = " ")
col = col - 1
print("")
row = row + 1
Name Your File: “ICS3UvLines.py”
Draw 3 vertical lines where the user controls the how many vertical stars are shown and how many spaces are in between the vertical lines
numRow = int(input("Rows: "))
numSpace = int(input("Spaces: "))
row = 0
while row < numRow:
#First Star
print("*",end = "")
#First set of Spaces
spaces = 0
while spaces < numSpace:
print(" ", end = "")
spaces = spaces + 1
#Second Star
print("*", end = "")
#Second set of Spaces
spaces = 0
while spaces < numSpace:
print(" ", end = "")
spaces = spaces + 1
#Last Star
print("*")
row = row + 1
Name Your File: “ICS3UhollowTriangle.py”
Draw the following shape, where the vertical size is controlled by the user
size = int(input("Enter size: "))
#Spaces before first row star
col = 1
while col <= size-1:
print(" ", end = "")
col = col + 1
#First Row Star
print("*")
#Middle set of stars
row = 1
while row <= size - 2:
#Spaces before middle set of stars
col = 1
while col < size - row:
print(" ", end = "")
col = col + 1
#First Middle star
print("*", end = "")
#Spaces between middle section of stars
col = 1
while col < row:
print(" ", end = "")
col = col + 1
#Second Middle star
print("*")
row = row + 1
#Final line of stars
col = 1
while col <=size:
print("*",end = "")
col = col + 1