leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python indentation rules

Estimated reading: 6 minutes 32 views

When writing essays, the teacher will tell us to leave two spaces in each paragraph, and these two spaces mark the beginning of a new paragraph. When writing programs, we also use a similar way to indicate the start and end of code blocks by indentation.

Recognize indentation

In the examples we’ve seen so far, we’ve written simple expression statements without indentation. However, to create compound statements, you need to use the important concept of indentation.

We can organize many lines of code into a code block, and each line of code begins with the same number of spaces. By looking at the number of spaces in front of the code line, we can determine the start and end of the code block, and this The number of spaces is the indentation .

Python judges the relationship between the current line of code and the previous line of code based on indentation. The advantage of indentation is to make the code look clearer and easier to read. If the code segment is relatively long, through indentation, we can quickly understand the organizational structure of the program, and it is not easy to make mistakes.

Next, let’s look at an example with many lines of code. Because the code segment of the program is relatively long, if there is no indentation, it will be difficult for us to distinguish the organizational structure of the code. This code just wants to illustrate the importance of indentation. You don’t need to care about the specific meaning. The code is as follows.

letter = input("please input:")
if letter == 'S':
    print ('please input second letter:')
    letter = input("please input:")
    if letter == 'a':
        print('Saturday')
    elif letter == 'u':
        print('Sunday')
    else:
        print('data error')
elif letter == 'F':
    print('Friday')
elif letter == 'M':
    print('Monday')
elif letter == 'T':
    print ('please input second letter')
    letter = input("please input:")
    if letter == 'u':
        print('Tuesday')
    elif letter == 'h':
        print('Thursday')
else:
        print('data error')
elif letter == 'W':
    print('Wednesday')
else:
    print('data error')

Hint: Few languages ​​take indentation as seriously as Python. For other languages, indentation is “better” for code writing, not “no no”, because indentation is just a matter of code writing style.

However, for the Python language, indentation is a syntax that tells us where Python code begins and ends. Compound statements in Python are represented by indentation. The advantage of this is that it reduces the degree of freedom of the programmer, which is conducive to a unified style, which makes it easier for people to read the code.

However, when writing Python programs, we also need to keep in mind that if the indentation is incorrect, the program may not run or will error out.

Length of Python indentation

It doesn’t matter how long you indent the code block, as long as you make sure that the entire code block is indented the same way. To this end, IDLE provides an auto-indent feature that positions the cursor to a specified position on the next line.

When we type a keyword like if that corresponds to the control structure, and press the Enter key, IDLE will start the automatic indent function, the code is as follows.

if 3>2 :
    print("Three is greater than two")

Normally, IDLE indents code one level by 4 spaces. If you want to change the default indent, you can select the “New Indent Width” command from the “Format” menu, as shown in Figure 1.

python new indentation width robort
python new indentation width

Figure 1
In the pop-up window, the default is 4 spaces, we can also modify this value according to our own needs, as shown in Figure 2.

python new indentation format
python new indentation format

Figure 2
For beginners, it should be noted that although the automatic indentation function is very convenient, we cannot rely on it completely, because sometimes automatic indentation may not fully meet our requirements, so after writing the program, we need to check it carefully .

Common Python indentation problems

missing indentation

As we mentioned earlier, the lines of code that are part of the conditional part after the if statement need to be indented. If like the code below (code below), forget to indent:

if 3>2 :
print("Three is greater than two")

Then, when compiling, Python will tell us that there is a syntax error and an indentation is required. The error message is shown in Figure 3.


image 3
Usually, by indenting the line of code immediately following the if statement, the error goes away.

Increase unnecessary indentation

What happens if you accidentally increase the indent where you don’t need it? Let’s look at a piece of code that adds indentation where it doesn’t need it. The code is as follows.

print("This is an apple")
    print("This is a banana")

When compiling, Python will give an error message that there is indentation that should not appear here, as shown in Figure 4.

python unexpected indent error
python unexpected indent error

Figure 4

Indentation causes logic errors in the program

The omission of indentation and the addition of redundant indentation described above are both grammatical errors, and it is up to us to judge whether the result obtained by running the program is the same as the expected result.

Let’s look at an example. Suppose there is a program that asks the user to enter a number and then prompts the user based on that number. When the input number is greater than 10, it will prompt that the number is greater than 10 and reset it to 0. If the number input by the user is not greater than 10, the number will be displayed directly. The code is as follows.

number = input ( "Please input a number: " )
if  ( int ( number )> 10 ):
    print ( "Your number is greater than ten and reset it zero" )
    number = "0"
print ( "Your number is: " + number )

When we enter 1, because 1 is not greater than 10, “Your number is: 1” will be displayed directly. If you enter 18, because 18 is greater than 10, the number will be reset to 0, and the displayed content will become “Your number is: 0”, as shown in Figure 5.

python logic and indentation
python logic and indentation

Figure 5
Next, we modify the indentation of the code, the code is as follows.

number = input ( "Please input a number: " )
if  ( int ( number )> 10 ):
    print ( "Your number is greater than ten and reset it zero" )
number = "0"
print ( "Your number is: " + number )

As you can see, the statement number=”0″ is now unindented, which means that number is reset to “0” regardless of whether the number entered is greater than 0, as shown in Figure 6.

python indentation affects logic
python indentation affects logic

Image 6
Even though the numbers we entered were still 1 and 18, the result was “Your number is 0”. As you can see, indentation sometimes affects the logic of the entire program.

Leave a Comment

CONTENTS