NEXT PAGE >
ARRAYS |
WHAT IS ITERATION
Iteration is a process of repeating the same or similar actions until an endpoint or criteria is met. In Python we can create loops to iterate through a process, the two types of loops we will use here are while loops and for loops.
WATCH THIS VIDEO TO GUIDE YOU THROUGH THIS SECTION
SECTION 1 | FOR I IN RANGE LOOPS
A for loop will always loop at least once, it will loop for the number of times set by the programmer or until it reaches a pre-set criteria and breaks the loop. There are two types of for loops we will cover here, firstly a for i in range loop and a for i in loop.
In both types of loops the i is a variable, you can actually use any variable name instead of i but i is used as it is short for index. The i becomes a special variable when used in a for loop and the value of i changes/iterates each time the loop loops. The code below demonstrates how the value of i changes as the loop iterates.
In both types of loops the i is a variable, you can actually use any variable name instead of i but i is used as it is short for index. The i becomes a special variable when used in a for loop and the value of i changes/iterates each time the loop loops. The code below demonstrates how the value of i changes as the loop iterates.
for i in range (3): print (i)
By running the above for loop you will see that the output will be 0,1,2. Computer start to count at zero so remember that the count starts at 0 and loops 3 times so the count will never actually get to the value stated in the brackets (3).
You can also stipulate a start and finish number for example:
You can also stipulate a start and finish number for example:
for i in range (2,5): print (i)
If you test the code above you will see the output will be 2,3,4.
PUTTING FOR LOOPS INTO GOOD USE
There are countless ways to use for i in range loops the below program demonstrate using the value of i in a for loop to output a given times tables in user friendly statements.
Notice in the code above that str(i + 1) was used.
- Firstly, str was used because you cannot concatenate a number with a string so str tell python to treat (i + 1) as a string
- Secondly, the value of (i + 1) was used because the starting value of i would have been 0 and in the last loop the value of i is 9 so by adding one it change the values used to 1 - 10. Alternatively the range could have been changed to for i in range (1,11)
SECTION 2 | FOR I IN LOOPS
For i in loops are used to loop through values and the i or variable name you use will be equal to each value in the loop rather than a number/count like it would be in a for i in range loop. If you want to loop through a value such as a string then you could use the following.
myString = ("King bob")
for i in (myString):
print (i)
Try the code above and you will see that the value of i becomes each letter of the string as the loop iterates. This is useful for inspecting each individual value and can be used for things such as password checks. The example below shows a for i in loop being used to check is a password contains a hash tag.
myString = ("King bob")
for i in (myString):
print (i)
Try the code above and you will see that the value of i becomes each letter of the string as the loop iterates. This is useful for inspecting each individual value and can be used for things such as password checks. The example below shows a for i in loop being used to check is a password contains a hash tag.
Code Editor
In the above code the break command is used to prevent the print statement running on every occasion that a hash tag is found in the string. Where possible using break statements should be avoided and this is further covered in later sections.
SECTION 3 | NESTED FOR LOOPS
The term nested for loop simply means putting a loop inside of a loop, this is common practice in programming so it is important to know the result of nesting. In previous tasks the value of i has been used to indicate the loop index. When nesting loops try to use different index names for each nested loop, for example use x or n on the nested loop as the index marker.
Looking at the nested loop below what do you think the outcome will be?
Looking at the nested loop below what do you think the outcome will be?
EXPAND THIS BOX TO SEE THE ANSWER
Tank 1
Fish 1
Fish 2
Fish 3
Fish 4
Tank 2
Fish 1
Fish 2
Fish 3
Fish 4
Fish 1
Fish 2
Fish 3
Fish 4
Tank 2
Fish 1
Fish 2
Fish 3
Fish 4
Each time the outer loop runs the inner loop will loop its entire range before returning to the outer loop. This is repeated until the outer loop have iterated it's entire range.
SECTION 4 | WHILE LOOPS
WATCH THIS VIDEO TO GUIDE YOU THROUGH THIS SECTION
While loops and for loops are both loops but have a clear difference in uses.
Take entering your password for example, some of the considerations could be:
A for loop would not be suitable for this scenario because, only if the user clicks 'sign in' should the loop run. The loop needs to run up to 3 times if the password is incorrect but only once if the password was correct the first time, therefore we do not know how many times this loop will actually need to run, it could be zero times to three times. This is where a while loop is needed. While loops run while a condition is met.
Look at the while loop below, the value 'bob' is assigned to the variable loginName. A while loop is created and has the condition to run while the variable userName is not equal to the loginName. Try the program, you will see the loop will continue to loop until you type 'bob' when prompted for the name.
- A for loop in your program will always iterate at least once.
- A while loop will only iterate if a condition is met.
- For loops are used when the number of iterations is known.
- A while loop is used when the number of iterations is not known.
Take entering your password for example, some of the considerations could be:
- If the user clicks 'sign in' the go to enter password
- If the user enters the password correct then login is successful
- If the use enters the password incorrect then display error message and ask the user to try again
- If the user enters the password wrong 3 times then redirect user to password problems page
A for loop would not be suitable for this scenario because, only if the user clicks 'sign in' should the loop run. The loop needs to run up to 3 times if the password is incorrect but only once if the password was correct the first time, therefore we do not know how many times this loop will actually need to run, it could be zero times to three times. This is where a while loop is needed. While loops run while a condition is met.
Look at the while loop below, the value 'bob' is assigned to the variable loginName. A while loop is created and has the condition to run while the variable userName is not equal to the loginName. Try the program, you will see the loop will continue to loop until you type 'bob' when prompted for the name.
Only after the loop has finished will the program move to the next line to print the welcome message. The loop is checking if the userName is not equal to the loginName, it is checking if a condition is True of False.
Because while loops have a boolean argument to the condition of the loop it is good practice to use the boolean operators True and False within while loop creation. Using the example from above and changing to use True or False statements to start and end the loop can be seen below.
Because while loops have a boolean argument to the condition of the loop it is good practice to use the boolean operators True and False within while loop creation. Using the example from above and changing to use True or False statements to start and end the loop can be seen below.
You can see that this program is much more complete than the first example and it uses False and True values to start and stop the loop as needed.
SECTION 5 | BREAKING A LOOP
One way to stop a while loop are to change the condition so the loop will not repeat, however the loop will not stop until it iterates back to the start of the loop. If you want to break the loop mid loop then you can use the break statement to break the loop immediately. This will work in both for and while loops as can be seen in the two example below.
The above code shows that an option for the user to exit is given, if the user chooses to exit by pressing 1, the break method is used and the loop will break.
SECTION 6 | PUTTING IT ALL TOGETHER
In this section we put all the skills together by creating two programs.
- PASSWORD CHECKER
- NUMBER GUESSING GAME
NUMBER GUESSING GAME WITH A WHILE LOOP
The video and code below show how to create a simple random number guessing game with a while loop.
ELEMENT |
DESCRIPTION |
EXAMPLE |
for value in |
Iterates over a sequence (like a list, tuple, or string) and executes a block of code for each item in the sequence. |
for fruit in ["apple", "banana"]: print(fruit) |
for num in range |
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (also by default), and stops before a specified number. |
for num in range(5): print(num) # Outputs: 0, 1, 2, 3, 4 |
Specifying Start and Stop |
Generates a sequence of numbers starting from the first specified number up to (but not including) the second specified number. |
for i in range(2, 5): print(i) # Outputs: 2, 3, 4 |
Specifying Step |
Adds a third argument to specify the increment. |
for i in range(0, 10, 2): print(i) # Outputs: 0, 2, 4, 6, 8 |
while |
Executes a block of code as long as the specified condition is true. |
count = 0 while count < 5: print(count) count += 1 |
break |
Used to change the behavior of loops during their execution. break: Exits the loop and continues executing the code after the loop. |
for number in range(10): if number == 5: break print(number) |
continue |
Skips the current iteration of the loop and continues with the next iteration. |
for number in range(5): if number == 2: continue print(number) |
pass |
A null operation; nothing happens when it's executed. It's used as a placeholder. |
for letter in "Python": if letter == "h": pass print(letter) |
PRINT AND COUNT
TASK
Create a program that
1: Asks the user to enter a number between 1 and 100, store the input in a variable
2: Ask the user to enter another number between 1 and 100, store the input in a variable
3: Produce a loop to count and print all of the numbers between the users first and second number
4: Count how many numbers that are between the users first and second number
5: When the loop has finish, in a user friendly statement output how many numbers there were.
EXAMPLE OUTPUT
Please enter a number between 1 and 100: 20
Please enter another number between 1 and 100: 30
Here are the numbers
21
22
23
24
25
26
27
28
29
There are 9 numbers between 20 and 30
Create a program that
1: Asks the user to enter a number between 1 and 100, store the input in a variable
2: Ask the user to enter another number between 1 and 100, store the input in a variable
3: Produce a loop to count and print all of the numbers between the users first and second number
4: Count how many numbers that are between the users first and second number
5: When the loop has finish, in a user friendly statement output how many numbers there were.
EXAMPLE OUTPUT
Please enter a number between 1 and 100: 20
Please enter another number between 1 and 100: 30
Here are the numbers
21
22
23
24
25
26
27
28
29
There are 9 numbers between 20 and 30
GREEN BOTTLES
The commonly known 'Green Bottle' rhyme goes:
"There are 10 green bottles hanging on the wall,
10 green bottles hanging on the wall,
and if 1 green bottle was to accidentally fall,
there would be 9 green bottles hanging on the wall"
10 green bottles hanging on the wall,
and if 1 green bottle was to accidentally fall,
there would be 9 green bottles hanging on the wall"
This repeats until the are zero green bottles.
TASK
Create a program that
1: Asks the user how many bottles they want to start with
2: Output the rhyme from the starting point to zero green bottles
Note: You can use a for or while loop for this task
TASK
Create a program that
1: Asks the user how many bottles they want to start with
2: Output the rhyme from the starting point to zero green bottles
Note: You can use a for or while loop for this task
Question 1: for i in range Loops
What will be the output of the following code?
for i in range(3): print(i)
A: 1 2 3
B: 0 1 2
C: 0 1 2 3
D: 1 2
EXPLANATION
Correct Answer: B) 0 1 2
Explanation: The range(3) function generates numbers starting from 0 and goes up to (but not including) 3. Therefore, i will take values 0, 1, and 2, resulting in the output 0 1 2.
Explanation: The range(3) function generates numbers starting from 0 and goes up to (but not including) 3. Therefore, i will take values 0, 1, and 2, resulting in the output 0 1 2.
Question 2: for i in Loops
What will the following loop print?
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
A: apple banana cherry
B: apple, banana, cherry
C: ['apple', 'banana', 'cherry']
D: fruit fruit fruit
EXPLANATION
Correct Answer: A) apple banana cherry
Explanation: This loop iterates over the list fruits and prints each element one by one. So, it will print each fruit on a new line.
Explanation: This loop iterates over the list fruits and prints each element one by one. So, it will print each fruit on a new line.
Question 3: while Loops
What will happen with the following code?
count = 1 while count < 4: print(count) count += 1
A: It will print 1 2 3 and stop.
B: It will print 1 2 3 4 and stop.
C: It will run indefinitely.
D: It will not print anything.
EXPLANATION
Correct Answer: A) It will print 1 2 3 and stop.
Explanation: The loop continues as long as count is less than 4. It starts at 1 and increments by 1 each time, printing 1, 2, and 3. When count becomes 4, the condition count < 4 is false, and the loop stops.
Explanation: The loop continues as long as count is less than 4. It starts at 1 and increments by 1 each time, printing 1, 2, and 3. When count becomes 4, the condition count < 4 is false, and the loop stops.
Question 4: Using a Flag/Condition to Start and Break the Loop
How can you exit a loop early using a flag or condition in Python?
A: By using the
exit
function.B: By using the
continue
statement.C: By using the
break
statement.D: By using the
return
statement.EXPLANATION
Correct Answer: C) By using the break statement.
Explanation: The break statement is used to exit a loop immediately, regardless of the loop’s condition. It’s often used with a flag or condition to break the loop when a certain condition is met.
Explanation: The break statement is used to exit a loop immediately, regardless of the loop’s condition. It’s often used with a flag or condition to break the loop when a certain condition is met.
Question 5: What is a Pre-condition Loop?
Which of the following best describes a pre-condition loop?
A: A loop that runs a specified number of times before checking the condition.
B: A loop that checks its condition at the end of each iteration.
C: A loop that checks its condition before each iteration begins.
D: A loop that runs indefinitely.
EXPLANATION
Correct Answer: C) A loop that checks its condition before each iteration begins.
Explanation: A pre-condition loop (e.g., a while loop) checks its condition before each iteration starts. If the condition is false initially, the loop will not execute.
Explanation: A pre-condition loop (e.g., a while loop) checks its condition before each iteration starts. If the condition is false initially, the loop will not execute.
Question 6: What is a Post-condition Loop?
What is a key difference between a pre-condition and a post-condition loop?
A: A post-condition loop always runs at least once.
B: A post-condition loop never runs more than once.
C: A post-condition loop does not require a condition.
D: A post-condition loop is the same as a pre-condition loop.
EXPLANATION
Correct Answer: A) A post-condition loop always runs at least once.
Explanation: A post-condition loop (e.g., a do-while loop in other languages, though Python doesn’t have this structure) checks the condition after the loop body has been executed. This guarantees that the loop will execute at least once, even if the condition is false from the start.
Explanation: A post-condition loop (e.g., a do-while loop in other languages, though Python doesn’t have this structure) checks the condition after the loop body has been executed. This guarantees that the loop will execute at least once, even if the condition is false from the start.
Question 7: Nested Loops
What is the output of the following nested loop?
for i in range(2): for j in range(3): print(i, j)
A: 0 1 2 3 4 5
B: 0 0 1 1 2 2
C: 0 0 0 1 1 1
D: 0 0 1 0 0 2
EXPLANATION
Correct Answer: D) 0 0 1 0 0 2
Explanation: The outer loop runs twice (i is 0 and 1), and for each value of i, the inner loop runs three times (j takes values 0, 1, and 2). The output shows each combination of i and j.
Explanation: The outer loop runs twice (i is 0 and 1), and for each value of i, the inner loop runs three times (j takes values 0, 1, and 2). The output shows each combination of i and j.
Question 8: Break in a Nested Loop
What happens when a break
statement is used inside a nested loop?
A: It breaks out of both loops.
B: It only breaks out of the inner loop.
C: It continues to the next iteration of the outer loop.
D: It exits the program.
EXPLANATION
Correct Answer: B) It only breaks out of the inner loop.
Explanation: When a break statement is used inside a nested loop, it only exits the innermost loop where the break is located. The outer loop will continue as normal.
Explanation: When a break statement is used inside a nested loop, it only exits the innermost loop where the break is located. The outer loop will continue as normal.