Lesson Objective
Understand Iteration and how to use WHILE and FOR Loops in Python programming.
KS3, GCSE, A-Level Computing Resources
Iteration is the process of repeating code until a condition is met.
Definite Iteration:
When code it repeated for a set number of times.
Indefinite Iteration:
When code is repeated for an unknown number of times.
FOR loops are examples of definite iteration. They loop a set number of times and can be executed in different ways.
name = input(“Enter your name: ”) for i in range (8): print (name) print (“Your name has been displayed 8 times.”)
Enter your name: Hamiela Hamiela Hamiela Hamiela Hamiela Hamiela Hamiela Hamiela Hamiela Your name has been displayed 8 times
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
apple banana cherry
for x in “banana”: print(x)
b a n a n a
While loops are examples of indefinite iteration. They repeat lines on code for an unknown number of times (until a condition is met).
choice = input(“What you you like to eat?: ”) while choice == “I dont know”: print (“No!!”) choice = input(“What you you like to eat?: ”) print (“Awesome, let’s go eat.”)
What do you want to eat: I dont know No!! What do you want to eat: I dont know No!! What do you want to eat: I dont know No!! What do you want to eat: Ice Cream Awesome, let’s go eat.
?
name = input(“Enter your name: ”) while name != “Mr Ahmed”: print (“Invalid User!!”) name = input(“Enter your name: ”) print (“Welcome Mr Ahmed”)
Enter your name: Hamiela Invalid User!! Enter your name: Jamie Invalid User!! Enter your name: Mr Vince Invalid User!! Enter your name: Mr Ahmed Welcome Mr Ahmed
?
toads = input(“Do you like toads? ‘y’ or ‘n’: ”) while toads != “y” AND toads != “n”: print (“Invalid Response!!”) toads = input(“Do you like toads? ‘y’ or ‘n’: ”) print (“Interesting response...”)
Enter your name: yea Do you like toads? ‘y’ or ‘n’: Enter your name: yeas Do you like toads? ‘y’ or ‘n’: Enter your name: yes Do you like toads? ‘y’ or ‘n’: Enter your name: y Interesting response...
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry