Repetition Structures
When we write computer programs we usually have the need to write a set of statements that we need to perform over and over again - in other words we need to repeat the same statements in a program many times. We do this through repetition structures. The two repetition structures we will be looking at are while and for loops. A loop is where you repeat statements over and over until you are through with what you want to accomplish.
Loops
There are two broad categories of loops - condition-controlled and count-controlled. A condition-controlled loop uses a true/false condition to control the number of times to do the loop. A count-controlled loop only performs the loop a specified number of times.
While Loop
This type of loop causes a set of statements to repeat as long as a condition is true. So While a condition is true - execute the statements in the loop. When the condition is false - skip to the statement following the last statement in the While loop. The SYNTAX is:
while condition:
statement
statement
etc.
The computer will check to see if the condition is true - if so, it will then execute the statements in the block sequentially. If the condition is false, the computer will skip the statements in the block and jump to the statement following the last statement in the while block. We call this a "pre-test" loop.
Problem - Infinite Loops
Every once in a while a loop NEVER stops executing - this is called an Infinite Loop condition. There must be something in the loop statements that will cause the loop to stop (cause the condition to be false). This is where we must have the correct logic in the loop to make this happen.
For Loop
The for loop is a count-controlled loop. The SYNTAX is:
for variable in [value1, value2, etc.]:
statement
statement
etc.
The first time through the loop, the variable (which you make up the name) is given the value1; the second time through the loop, the variable is given the value2; etc. until the last time through the loop the variable is given the valuex (last value).
For loop using the Range Function
PYTHON has a built in function called range() that simplifies the count-controlled loop.
Continue and Break
The continue and break keywords are used to change the normal flow of loops on certain conditions.
continue - skip rest of statements in the loop and start next iteration.
break - skip rest of statements in the loop (if any) and exit loop.
Counting - Calculating a Running Total
A running total is a sum of numbers that accumulates with each time through the loop (iteration). The variable that is used to keep the running total is called an Accumulator.
Example: total = total + 1 (the "new" total value - on the left side - is equal to the old total value + 1)
Sums
A sum uses the old total, adds another variable to the old total to create a new total that is used in the next expression:
total = total + number
Exercises
The examples below are written in "script" mode.
Example: while_loop.py
# continuously ask user input till it is a positive integer
usr_string = 'not a number'
while not usr_string.isnumeric():
usr_string = input("Enter a positive integer: ")
- while loop allows us to execute block of statements until a condition is satisfied
Results:
Enter a positive integer: abc
Enter a positive integer: 1.2
Enter a positive integer: 23
Example: for_loop.py
number = 9
for i in range(1, 5):
mul_table = number * i
print("{} * {} = {}".format(number, i, mul_table))
- traditional iteration based loop can be written using range function
- by default start=0, step=1 and stop value is not inclusive
- iterating over variables like list, tuples, etc. will be covered later
Results:
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
Example: loop_with_continue.py
prev_num = 0
curr_num = 0
print("The first ten numbers in fibonacci sequence: ", end='')
for num in range(10):
print(curr_num, end=' ')
if num == 0:
curr_num = 1
continue
temp = curr_num
curr_num = curr_num + prev_num
prev_num = temp
print("")
- continue can be placed anywhere in a loop block without having to worry about complicated code flow
Results:
The first ten numbers in fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Example: loop_with_break.py
import random
while True:
# as with range() function, 500 is not inclusive
random_int = random.randrange(500)
if random_int % 4 == 0 and random_int % 6 == 0:
break
print("Random number divisible by 4 and 6: {}".format(random_int))
- while True: is generally used as infinite loop
- randrange has similar start, stop, step arguments as range
Results:
Random number divisible by 4 and 6: 240