The use of the three basic programming constructs used to control the flow of a program: Iteration (count- and condition-controlled loops)
2.2.1 Programming Fundamentals
Practise exam questionsProgramming Fundamentals — Note 4 of 6
Practical use of the techniques, Understanding of each technique
Iteration means repeating a set of instructions. There are two main types: count-controlled loops (FOR loops) that repeat a fixed number of times, and condition-controlled loops (WHILE and DO-UNTIL) that repeat until a condition changes. Loops can also be nested, meaning one loop inside another.
range(stop) starts at 0 and stops BEFORE the stop value: range(5) gives 0, 1, 2, 3, 4.range(start, stop, step) sets where to start, where to stop (not included) and how much to change by. A negative step counts down, so to include 0 the stop value must be -1.total = 0 BEFORE the loop, then add each value inside the loop with total += value.count = 0 BEFORE the loop, then add 1 inside an if whenever the condition is met: count += 1.False. while team != "stop" is common.while hours != 0 is safer than while hours > 0 (user could enter -1 and bypass the check).for x in list: — x is the item VALUE, not an index. Do not then try to access list[x] as x is not an index number.for i = 0 to 4 INCLUDES the end value (0 to 4). Python's range(5) gives the same values because the stop value is excluded. Watch for off-by-one errors when converting between them.# FOR loop (count-controlled)
for i in range(5):
print("Iteration", i)
# WHILE loop (condition-controlled)
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")# Count up: 0, 1, 2, 3, 4 (the stop value 5 is NOT included)
for i in range(5):
print(i)
# range(start, stop, step): 2, 4, 6, 8, 10
for i in range(2, 11, 2):
print(i)
# Count down: 10, 9, ... 0 (stop at -1 so that 0 is included)
for i in range(10, -1, -1):
print(i)# Number condition: variable set BEFORE the loop
total = 0
while total < 100: # repeats while the condition is True
total += 10 # variable must change INSIDE the loop
# Text condition: repeat until the user types exit
text = ""
while text != "exit":
text = input("Type something (or 'exit' to quit): ")
print("You typed:", text)total = 0
count_over_10 = 0
for i in range(5):
num = int(input("Enter a number: "))
total += num # keep a running total
if num > 10: # count the numbers over 10
count_over_10 += 1 # increment by 1
print("Total:", total)
print("Numbers over 10:", count_over_10)total = 0
count_over_10 = 0
num = int(input("Enter a number (negative to stop): ")) # first input BEFORE the loop
while num >= 0: # run until a negative number is entered
total += num # keep a running total
if num > 10: # count the numbers over 10
count_over_10 += 1
num = int(input("Enter a number (negative to stop): ")) # next input as the LAST line
print("Total:", total)
print("Numbers over 10:", count_over_10)Ready to test yourself?
Practise 2.2.1 questions