Indentation

If you are to use Python for anything beyond simple one- or two-line programs, you’ll need to use some form of compound statement, such as a conditional (if) statement or some form of loop. A compound statement usually consists of an opening clause (such as if x < y) followed by one or more statements that are to be run as part of the compound statement.

If you’re used to other languages such as C++, C# or Java, you’ll also be used to the syntax these languages require for compound statements. If you were taught these languages properly (either by self-study from a book or from a good teacher), you will have been taught to indent each line within a compound statement to improve the readability of your code. However, in these languages, indentation is optional, in the sense that, if you didn’t indent your code at all, or used haphazard indentation where each line was indented by a different amount, it would make no difference to the correctness of the code. If it was logically and syntactically correct, it would still run and give you the correct results. [However, a good teacher would still dock marks if you didn’t indent your code, so it makes code difficult to understand and maintain.]

Python promotes indentation from ‘just a good idea’ to ‘essential’. Statements within a compound statement must be indented relative to the opening line of the compound statement, and the indentation must be consistent: that is, each line must be indented by the same amount.

Although we haven’t yet studied conditional statements or loops in detail, we can use a few simple examples of these statements to illustrate Python’s indentation requirements.

Before I present the code, I will make a recommendation about project management. Most of the code we’ll study from now on will involve programs that span several lines, so it can get tedious and repetitive if you try to enter these programs into an interactive Python console. If you’re using Visual Studio to run your Python examples, I’d strongly recommend that you create a new Python project and enter your code there, rather than use the interactive console.

Right, now on to our first complete program. The following code asks the user to input an integer. If the user types ‘stop’ instead, the program quits; otherwise, it tests to see if the user has entered a valid integer, and then prints out a string showing the multiplication table (up to 12) for that integer.

while True:
    num = input('Enter an integer (or \'stop\' to quit): ')
    if num == 'stop':
        break
    if not num.isdigit():
        print('Not an integer. Try again.')
    else:
        num = int(num)
        table = ''
        for i in range(13):
            table += str(num * i) + ' '
        print(table)

We’ll leave a full discussion of the if statement and the while and for loops until later, but it’s worth noting a few points here.

First (and very important): in Python, the opening line of any compound statement must end with a colon (:). This is probably the biggest bugbear that will catch out programmers used to languages like C++, C# and Java.

Second, the conditions in ‘if’ statements and loops need not be enclosed in parentheses (although they can be if you really insist on it).

Now, as to the code itself:

Line 1 creates an infinite loop, since the condition for the while loop is given as True, which obviously is always, well, true. This isn’t exactly best programming practice, but in this case it’s OK since we provide a way for the user to exit the loop (by typing ‘stop’ at the input prompt). The input() function reads input from the console and returns the result as a string.

The ‘break’ statement on line 4 breaks out of the current level of loop. In this case, at the point where ‘break’ occurs, we are within only the top-level while loop, so the program breaks out of this loop.

Line 5 checks to see if the user entered a valid integer by using the isdigit() function, which is part of the string library. It checks that the string contains at least one character, and that all the characters are integers. Thus it will return false if the user enters a float (with a decimal point) or any string containing letters.

If the input passes the test (that is, it’s an integer), line 8 converts it to an integer (remember that ‘input’ returns the input as a string, and we can’t perform arithmetic on strings). Line 9 initializes table to a string with no characters. Line 10 uses a for loop to iterate the value of i from 0 up to one less than the argument of range(13), so i ranges from 0 to 12.

Line 11 is part of the for loop, and extends table by attaching the result of num * i, converted to a string. Finally, line 12 prints out the result.

It’s important to note the indentation levels used here. The entire program is part of the opening while loop, so everything after line 1 must be indented relative to the opening while. The if statement on line 3 contains only a single statement, namely the ‘break’ on line 4, so line 4 must be indented relative to line 3. Line 5 opens a new ‘if’ statement, so again we must indent statements within it. The ‘else’ on line 7 has the same logical level as the ‘if’ on line 5, so it reverts to the same indentation level as line 5. All the remaining statements (lines 8 to 12) are part of the ‘else’, so they are all indented to the same level. Finally, line 11 is part of the ‘for’ loop, so must be indented relative to line 10.

Exercises

  1. Modify the above code by indenting line 12 so it has the same level as line 11. Try to predict the result before you run it. Is this valid Python code? What will be printed out?
See answers

Yes, it is valid Python code. It moves the final print(table) statement to be within the for loop, so ‘table’ is printed out after each multiplication, rather than just at the end. Sample output:

Enter an integer (or ‘stop’ to quit): 12
0
0 12
0 12 24
0 12 24 36
0 12 24 36 48
0 12 24 36 48 60
0 12 24 36 48 60 72
0 12 24 36 48 60 72 84
0 12 24 36 48 60 72 84 96
0 12 24 36 48 60 72 84 96 108
0 12 24 36 48 60 72 84 96 108 120
0 12 24 36 48 60 72 84 96 108 120 132
0 12 24 36 48 60 72 84 96 108 120 132 144

2. Write a program that calculates and displays the first n Fibonacci numbers. The Fibonacci sequence starts with f_1=1, f_2=1 and then every succeeding number is the sum of previous two, so f_{n+1}=f_{n}+f_{n-1}. Your program should ask for an integer input, check if the user entered ‘stop’, then check that the input is a valid integer, then calculate the first n Fibonacci numbers and print them out on a single line.

See answers
while True:
    num = input('How many Fibonacci numbers (\'stop\' to quit)?: ')
    if num == 'stop':
        break
    if not num.isdigit():
        print('Not an integer. Try again.')
    else:
        fib1 = 1
        fib2 = 1
        num = int(num)
        table = str(fib1) + ' ' + str(fib2)
        for i in range(num - 2):
            fib3 = fib1 + fib2
            table += ' ' + str(fib3)
            fib1 = fib2
            fib2 = fib3
        print(table)

Typical output of this program is
How many Fibonacci numbers (‘stop’ to quit)?: 20
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
How many Fibonacci numbers (‘stop’ to quit)?: stop
Press any key to continue . . .

Leave a Reply

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