Week3B Preread: Basic Loops - for and while#
Loops are statements that repeat other statements (called the action). For loops are generally used as counted loops, in which the number of repetitions is specified ahead of time. In Python, for loops are frequently used to perform the same operation(s) on everything stored in a sequence. while loops are conditional loops, which repeat statements as long as an expression is True, or until something happens.
For loops#
Loops using range#
For loops are used to repeat other statements (called the action) a specified number of times. The easiest way to specify how many times is to use the range function (which we will revisit later in the course). The range function generates a sequence of numbers. Called with an integer n, range(n) creates a sequence of n integers. By using an iterator variable (a variable the defines where along the sequence you want to loop over you currently are) and the in operator along with the range function, we can specify how many times to repeat an action. The general form to specify repeating an action n times is:
for itervar in range(n):
action
# rest of code
This says to repeat the action n times. The iterator variable itervar iterates through all of the numbers generated by the range function, and for each value of the iterator variable, the action is executed. The action can be any number of valid statements. All of the statements in the action must be indented to the same level (typically 4 spaces). For historical reasons, the iterator variable (itervar) is frequently named i.
For example, the following for loop specifies repeating the action of printing a single ‘!’ 5 times.
for i in range(5):
print('!', end='')
print('\nOK')
This produces the output:
!!!!!
OK
The iterator variable i iterates through the 5 values produced by the range function, and for each of those five values it prints a single exclamation point, on the same line. Specifying end = ‘ ’ keeps all of the exclamation points on the same line, with nothing printed in between them. After the loop, printing the newline character moves down to the next line, where ‘OK’ is printed.
Note that in this example, the iterator variable i was not used in the action; it simply specified how many times to execute the action. In some cases, however, using the value of the iterator variable in the action is desired.
The sequence that is produced by range begins with 0, and ends at n-1. For example, range(4) creates a sequence of 4 integers: 0, 1, 2, 3.
The following loop prints the integers 0 to 3 in a column, and then ‘OK’ after the loop.
for i in range(4):
print(i)
print('OK')
0
1
2
3
OK
In this example, the iterator variable i iterates through the values in the sequence produced by the range function. For every value of the iterator variable, the action is executed. The action in this case was to print the value of i (and the newline character, which print does by default). So, when i had the value 0, 0 was printed. Then, the iterator variable i got the value of 1, and 1 was printed. Then, i got the value of 2 and 2 was printed. Then, i got the value of 3 and 3 was printed. Once the iterator variable has iterated through all of the values in the sequence, the loop is over. Once the action was repeated 4 times, for every value in the sequence 0, 1, 2, 3, the next statement in the code after the loop was executed, which printed ‘OK’.
The following prints the integers 0 to 2, each of which is followed by a colon, space, and ‘!’.
for num in range(3):
print(f'{num}: !')
0: !
1: !
2: !
Although frequently named i, the iterator variable can have any name. In this case, the iterator variable num iterated through the values 0, 1, and 2. The action that was executed for each value of num was to print num in a formatted line including a colon and exclamation mark.
So, again, sometimes the iterator variable is just used to specify how many times to repeat an action, as in:
for i in range(3):
print('*')
*
*
*
Sometimes the value of the iterator variable is used in the action, as in:
for i in range(3):
print(i)
0
1
2
Looping through sequences#
A for loop can be used in Python to iterate through the items in any sequence, and perform the same action for each one. The general form is
for itervar in sequence:
action
# rest of code
There is a variable, itervar, that iterates through all of the items in the sequence in order. For each item, the action is executed.
The following loops through all of the items in the list somenums and prints each in a sentence.
somenums = [4, 33, 11]
for n in somenums:
print('The number is', n)
The number is 4
The number is 33
The number is 11
At the beginning of the loop, the iterator variable n gets the value of the first number in the list, which is 4, so the action prints ‘The number is 4’. Then, after the action has been executed in its entirety (in this case, it is just one statement), the iterator variable gets the next number in the list, 33. This is printed, and then n gets the value 11, which is printed. Once the action has been executed for all of the numbers in the list, the loop ends.
After the loop, the iterator variable n stores the last item from the list.
somenums = [4, 33, 11]
for n in somenums:
print('The number is', n) print('n is ', n)
The number is 4
The number is 33
The number is 11
n is 11
The list does not need to be stored in a variable. The following will produce identical results.
for n in [4, 33, 11]:
print('The number is', n) print('n is ', n)
Another example illustrates looping through a list that stores different types of items, and displaying the type of each:
mixedlist = [33, 'hi', False]
for m in mixedlist:
print(type(m))
<class 'int'>
<class 'str'>
<class 'bool'>
Since strings are sequences, for loops can iterate through the characters in a string. For example, the following prints each character in a string followed by a space:
myword = 'hello'
for c in myword:
print(c, end = ' ')
h e l l o
Calculating Running Sums#
A useful application of a loop is to calculate a running sum. A running sum typically starts at 0, and then numbers are added to the sum one at a time. For example, the sum 0+1+2+3+4+5 would start at 0, then 0+1 which is 1, then 1+2 which is 3, then 3 + 3 which is 6, then 6 + 4 which is 10 and finally 10 + 5 which is 15.
The following code accomplishes this, using a running sum variable runsum, and then printing the overall sum.
runsum = 0
for i in range(6):
runsum = runsum + i
print('The sum is', runsum)
The sum is 15
As the iterator variable i iterates through the values 0 through 5, each is added to the result that has already been stored in runsum. The action of the loop is simply to add to the running sum. Printing is only done after the loop, when the overall sum has been calculated.
In another example, the user is prompted for 4 numbers. Each of the numbers that the user enters is added to a running sum.
runsum = 0
for i in range(4):
num = float(input('Enter a number: '))
runsum = runsum + num
print('The sum is', runsum)
Enter a number: 33
Enter a number: 4.5
Enter a number: -5
Enter a number: 2.8
The sum is 35.3
In this case, instead of adding the iterator variable i to the running sum, the numbers that the user enters into the variable num are added to the running sum.
A running sum can also be calculated from the numbers in a list.
runsum = 0
for n in [4, 33, 11]:
runsum = runsum + n
print('The sum is', runsum)
The sum is 48
Conditional Loops#
While and while-else#
A loop is a statement that repeats other statement(s), which are called the action of the loop. A conditional loop repeats the action as long as an expression is True, or until something happens. In Python, the while statement is used as the conditional loop. The general form is:
while expression:
action
# rest of code
The while loop begins by evaluating the expression (which is also sometimes called the condition). If the expression is True, then the action is executed. So far, that is exactly like an if statement! But, after the action has been executed in its entirety, control goes back to the top of the loop, and the expression is evaluated again. If the expression is True this time, the action is executed again. Then, the expression is evaluated, and if it is True, the action is executed again. This continues as long as the expression is True. When the expression becomes False, the while loop ends and control goes to the rest of the code after the while loop. Just like selection statements and the for loop, the action can consist of any number of statements, which must be indented to the same level (typically 4 spaces).
For example, the while loop
x = 2
while x < 5:
x = x + 1
print(x)
print('!')
would result in this output:
3
4
5
!
To begin with, the value of the variable x is 2, which is less than 5. So, the action is executed which increments x to get the value of 3, and this (3) is printed. 3 is less than 5, so the action is executed again, incrementing x to get the value of 4, and printing 4. 4 is still less than 5, so the action is executed again, incrementing x to get the value of 5, and printing 5. Then, when the expression is evaluated, 5 is not less than 5 so the expression is False and the while loop ends. The statement that prints ‘!’ is after the loop, so it only executes once. Note that in this example the two statements in the action are indented 4 spaces.
Since the expression is always evaluated before the action in a while loop, it is possible that the action will not be executed at all. This could occur if the expression is False the first time that it is evaluated. The code
x = 20
while x < 5:
x = x + 1
print(x)
print('!')
would result in this output:
!
Since 20 is not less than 5, the action of the loop is skipped and the code just prints ‘!’.
It is important that the action must change something in the expression so that eventually it becomes False. If this never happens, an infinite loop occurs. To exit from an infinite loop, hit Control-C in Windows or Linux, or Command-C on Macs for most Python environments. Others may be different; for example, in Jupyter notebooks it is necessary to choose Kernel and then Interrupt, or hit the square “interrupt the kernel” icon.
An optional else clause can be added to a while loop, which specifies an action to be executed when the condition becomes `False. The general form is
while expression:
whileaction
else:
elseaction
# rest of code
For example, we could print the value of x that ends the action of the `while loop:
x = 2
while x < 5:
x = x + 1
print(x)
else:
print('We are done at ', x)
print('!')
3
4
5
We are done at 5
!
The else clause only works if the condition becomes False. Any other method of ending the loop would not result in the execution of the else clause.
4.2.2 Error Checking#
When there is user input into a program, there is almost always a valid range of values. For example, if the user is prompted to enter the length of the sides of a square, the user should enter a positive number. There might be a tighter range than that; for example, it may be specified that the sides should be in the range from 5 to 7 meters. Error-checking means checking the user’s entry for errors. More specifically, error-checking generally involves continuing to prompt the user and read in the user’s entry until a valid value is entered. In Python, this can be accomplished using a while loop.
For example, the following code prompts the user for a positive number, and loops to continue prompting the user until the user does enter a positive number. For now, we will assume that the user enters a number, although we will see functions in Chapter 5 that will allow us to check to make sure that the user in fact entered a number.
number = input('Enter a positive number: ')
number = float(number)
while (number <= 0):
number = input('Seriously! Enter a positive number: ')
number = float(number)
print('Thanks for entering', number)
Running the code might result in the following.
Enter a positive number: -5
Seriously! Enter a positive number: -11.1
Seriously! Enter a positive number: 3
Thanks for entering 3.0
The user was prompted for a positive number, but entered -5. Since the input function returns a string, the user’s input is cast to the type float. Since that was a negative number (less than or equal to 0), the action of the loop was executed. In the action, the user was again prompted for a positive number (‘Seriously!’), but again the user entered a negative number. So, the action was executed again but this time the user entered 3. Since 3 is not less than or equal to 0, the False condition causes the loop to cease executing. The code after the loop then printed the positive number that the user finally entered. Notice that prompting the user is repeated before the loop, and also in the action of the loop. This is so that there will be a new value of number every time the condition is evaluated.
Of course, it is possible that the user will follow instructions the first time and enter a positive number. In that case, running the code might result in the following.
Enter a positive number: 5.2
Thanks for entering 5.2
Since the condition is evaluated at the top of the loop, and it was already False, the action of the loop was skipped entirely.
Counting in a while loop#
With conditional loops, it is not known ahead of time how many times the action of the loop will be executed. However, it is often useful to count how many times the action ended up being executed.
This can be accomplished by creating a counter variable, initializing it before the loop, and incrementing it by one in the action of the loop (so it is incremented every time the action is executed). For example, when error-checking we may want to know how many tries it took before the user entered a correct value.
counter = 0;
number = input('Enter a positive number: ')
number = float(number)
counter = counter + 1
while (number <= 0):
number = input('Seriously! Enter a positive number: ')
number = float(number)
counter = counter + 1
print('Thanks for entering', number)
print('It took you', counter, 'tries.')
Enter a positive number: -9
Seriously! Enter a positive number: 33 Thanks for entering 33.0
It took you 2 tries.