1. One of the benefits of a WHILE loop is that you can use it when you are unsure of how many iterations you wish to carry out.
2. In the following snippet of code, when will the last line: "print("Finito") be executed?
3. A disadvantage of FOR loops is that you can only use them when you are not aware of how many iterations you need at the start.
4. There are two functions here - what does each of them do?
def main():
using_a_while_loop()
using_a_for_loop()
def using_a_while_loop():
print("Using a While Loop")
i=1
while i < 11:
number=2
print(i*number)
i =i+1
#This uses a for loop
def using_a_for_loop():
print("Using a For Loop to do the same thing")
for i in range(1,11):
number=2
print(i*number)
#i =i+1 #this is not needed as the for loop automatically goes up in the range
main()
Both loops check to see if the number 1 is a prime number
Both loops produce the same output: printing out numbers 2,4,6,8,10,12,14,16,18,20
The first one produces an output of 1 to 11 and the second produces an output of 2 to 12
Both loops produce the same output: printing out numbers from 2 to 11 (2,3,4,5,6,7,8,9,10,11)
5. Analyse the following code that utilises a WHILE loops. What does it do?
6. What happens if the user presses 'y'?
7. In the following code, what does line 1 mean?
8. What is the output of the following code that uses a for loop?
#set a flag to false
found=False #this is the initial assumption
for x in range(0,11):
#if x is equal to 5 then set the found flag to True and exit the loop!
if x == 5:
found=True
break #this exits the loop
else: #if 5 is not found, then continue and print all values for x
print(x)
0,1,2,3
0,5,10
0,1,2,3,4
0,1,2,3,4,5,6,7,8,9,10,11
9. In the following code that uses a for loop, what are the first three numbers that are output if a =1; b=1
10. Can you predict the output of the following code?
11. What is the output of the following code?
def main():
for i in range(1,10,5):
print(i)
main()
10,5,1
1,5,10
1,6
1,2,3,4,5
12. The following code prints out 1,3,5,7,9. What would you change in line 2 to make it print 9,7,5,3,1?
13. What do you need to change for this code to print numbers from 1 to 10? (instead of 1 to 9)
14. ___________________ loops are also called WHILE loops or WHILE-ENDWHILE statements
15. A ________________loop (FOR loop) iterates the number of times specified in the loop
16. An infinite loop can occur with all condition-controlled loops but not with a count-controlled loop.
17. With a REPEAT UNTIL condition-controlled loop, the code in the loop is executed at least once.
18. Iteration is the process of __________________________ to achieve a particular target or goal
20. condition-controlled loops - repeat until ….