While loops

Python has two basic loops: while and for. Of these two, while is probably the simpler, so we’ll start with a look at it.

The basic syntax of a while loop is:

while [condition is True]:
    do something
    do something else
else:
    do something when condition is False

The ‘condition’ in the first line is a boolean expression such as those we studied earlier. As long as this condition is True, the statements in the first block will be executed. If the ‘condition’ is False, the ‘else’ clause is activated, and any statements within this block will be run. The ‘else’ block is optional, and is a feature not found in most other traditional languages.

The loop can be ended with a break statement anywhere within its block. This transfers control to the first statement after the entire loop (not to the else block within the loop).

A continue statement anywhere within the loop causes the rest of the code in that iteration of the loop to be skipped, and control passes back to the opening while statement. Note that continue does not exit the loop; it merely skips one iteration within the loop. If you want to exit the loop entirely, use break.

Here’s an example:

word = 'go'
while (word != 'stop'):
    word = input('Enter some text: ')
    if word.isdigit():
        print('You\'ve entered an integer:', word)
        continue
    elif word.isupper():
        print('The string is UPPERCASE:', word)
    elif word.islower():
        print('The string is lowercase:', word)
    else:         # Mixed upper and lowercase
        break
    word = word.lower()
else:
    print('Quitting the program.')

After initializing word on line 1 (remember all variables in Python must be initialized before they can be used), we enter the loop. The loop’s condition is True as long as word is not ‘stop’. We ask the user to enter some text, then test if the user entered only digits. If so, the continue on line 6 skips the rest of the loop (including the else on line 14) and returns control back to the start of the loop on line 2.

If the user entered text that is entirely uppercase, we print the message on line 8; if it’s all lowercase, we print the message on line 10. If the entered text is none of: integer, all upper or all lowercase, the break on line 12 causes the loop to be exited immediately, so the program ends (without executing the else clause, so the message ‘Quitting the program’ is not printed).

If the user enters the string ‘stop’ (in either all upper or all lowercase, but not mixed), the condition in line 2 is False, and the else clause in line 14 will run, after which the program ends.

If the program reaches line 13 (which will happen only if the continue in line 6 and the break in line 12 are not reached), word is converted to lowercase so it can be compared with ‘stop’ in line 2.

Exercise

Write a program that asks the user to enter a positive integer. The program should check that the entered datum is a positive integer, and quit if anything else is entered. For a valid input, the program should then calculate the factorial of that integer and print it out, followed by a prompt for the user to enter another integer. The program should quit if the user enters anything other than a positive integer.

As a reminder, the factorial of an integer n is defined as n!\equiv n\times (n-1) \times (n-2) \times \ldots \times 2 \times 1. You should use the while loop as the only loop structure in this program.

See answer
num = 1
while num > 0:
    num = input('Enter a positive integer: ')
    if not num.isdigit() or int(num) < 1:
        break
    num = int(num)
    fac = num
    while num > 1:
        fac *= num - 1
        num -= 1
    else:
        print(fac)

We use two nested while loops. The outer loop reads the input and tests that the user has entered a positive integer (line 4). If not, the outer loop breaks on line 5, and since nothing follows the outer loop, the program quits.

If num is a positive integer, it is converted to an int on line 6 (remember that all input is read as strings). The variable fac is initialized to num and successively multiplied by a decreasing sequence of integers in the inner while loop. When num is reduced to 1, the condition in the inner loop becomes False, and its else clause is run, which prints out the factorial num!. Note that at this point, the value of num is 1 (not 0) so when control returns to the outer while loop, the condition num > 0 is True, and the loop continues with another request for input.

As a side note, since Python has no limit (other than computer memory) on the size of integer it can represent, you can get the factorial of some quite large numbers. Pocket calculators are usually restricted to numbers with a couple of hundred digits, but you can get a lot higher in this program. For example, try calculating 10000! (Be prepared to do a lot scrolling in the output window to see the full answer.) Try modifying the above program to print out the number of digits in n! rather than the factorial itself. Hint: use the len() function. You will find that 10000! has 35660 digits.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.