1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 3. Iteration


Lesson Objective

Understand Iteration and how to use WHILE and FOR Loops in Python programming.


Lesson Notes

Iteration

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 (Definite Iteration)

FOR loops are examples of definite iteration. They loop a set number of times and can be executed in different ways.

Iterating a range

Code:

name = input(“Enter your name: ”)
for i in range (8):
   print (name)
print (“Your name has been displayed 8 times.”)

Cmd Output:

Enter your name: Hamiela
Hamiela
Hamiela
Hamiela
Hamiela
Hamiela
Hamiela
Hamiela
Hamiela
Your name has been displayed 8 times  

Iterating through a list

Code:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
   print(x)

Cmd Output:

apple
banana
cherry 

Iterating through a string

Code:

for x in “banana”:
   print(x)

Cmd Output:

b
a
n
a
n
a  

WHILE Loops (Indefinite Iteration)

While loops are examples of indefinite iteration. They repeat lines on code for an unknown number of times (until a condition is met).

Code:

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.”)

Cmd Output:

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.    

?

Code:

name = input(“Enter your name: ”)
while name != “Mr Ahmed”:
   print (“Invalid User!!”)
   name = input(“Enter your name: ”)
print (“Welcome Mr Ahmed”)

Cmd Output:

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    

?

Code:

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...”)

Cmd Output:

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...

Nested Loop

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

Code:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
   for y in fruits:
      print(x, y)

Cmd Output:

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry    

3