Introduction to Python from zero (5) indentation and selection

  • 2020-04-02 13:41:47
  • OfStack

The indentation

The most distinctive feature of Python is the code that is indent into blocks. Let me give you an example of an if select structure. If is followed by a condition, and if the condition is true, a code block belonging to the if is executed.

Let's look at the C language first (note that this is C, not Python!).


if ( i > 0 )
{
    x = 1;
    y = 2;
}

If I > For 0, we will do the two assignments included in the parentheses. The parenthesis contains the block operation, which belongs to if.

In Python, for the same purpose, this passage goes like this


if i > 0:
    x = 1
    y = 2

In Python, you get rid of the I > The parentheses around 0, which remove the semicolon at the end of each sentence, and the curly braces for blocks disappear.

If... The following :(colon), and then the four Spaces before x = 1 and y =2. By indentation, Python recognizes that these two statements belong to the if.

Python's reason for doing this is purely to make the program look good.

If statement

Write a complete program called ifdemo.py. This program is used to implement the if structure.


i = 1
x = 1
if i > 0:
    x = x+1
print x

$python ifDemo. Py   # run

The condition is True when the program runs to if, so execute x = x+1.

Print x statement has no indentation, so it's outside of if.

If you change the first sentence to I = -1, then if encounters False, and x = x+1 belongs to if, this sentence is skipped. Print x has no indentation, it's outside of if, no skip, go ahead.

This indentation of four Spaces to indicate affiliation, as you'll see later. Forced indentation makes the program more readable.

More complex if selection:


i = 1
if i > 0:
    print 'positive i'
    i = i + 1
elif i == 0:
    print 'i is 0'
    i = i * 10
else:
    print 'negative i'
    i = i - 1
print 'new i:',i

We have three blocks here, which are if, elif, else leads.
Python detects conditions. If the condition of if is found to be false, it skips the block immediately following it and detects the condition of the next elif. If it's still false, execute the else block.
The above structure divides the program into three branches. The program executes only one of three branches, depending on the condition.

The entire if can be placed in another if statement, that is, the nested use of the if structure:


i  = 5
if i > 1:
    print 'i bigger than 1'
    print 'good'
    if i > 2:
        print 'i bigger than 2'
        print 'even better'

If I > The block after 2 is indented with four Spaces relative to the if to indicate that it belongs to the if, not the outer if.

conclusion

The colon after the if statement

Indentation with four Spaces indicates membership, and you can't indent it in Python


if  < conditions 1>:
    statement
elif < conditions 2>:
    statement
elif < conditions 3> : 
    statement
else:
    statement


Related articles: