Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. If else,for,while, etc. This article introduces the use of flow control keywords in Python. If you have any questions or needs, please feel free to leave a message.

preface

There is a saying that a program consists of a process plus a data structure. This is true of any program. Having spent several pages introducing various data structures in Python, this article follows with a look at flow control. Data structures are basically used to store data, and processes are used to control the operation of the system.

Process control

Process control has three kinds of structure, one is sequence structure, one is selection (branch) structure, one is cycle structure. Sequential structure: the process of executing code from beginning to end, without repeating any line of code and skipping any line of code. That’s what one step at a time means. Selection (branching) : This is when the program executes different code based on different criteria, such as whether someone is an adult based on their age. Loop structure: let the program loop through a piece of code. The sequential process is not covered here.

Select structure (if,else) :

If statement

Using only if statements is the simplest form of Python. If the condition is met, the expression is executed. The expression execution is skipped. The pseudocode is:

ifCondition true: code blockCopy the code

If the condition following if is true, the code block is executed. Otherwise, execution of the code is skipped. The flow chart is:That is, if only the expression is true, the block is executed, if not, the block is terminated. Here is a simple example: print a if the condition a==1 is met, otherwise skip the statement.

a = 1
if a == 1:
    print(a)
Copy the code

If the else statement

The if else statement is a variant of if, executing block 1 if the condition is met, and block 2 otherwise. The pseudocode is:

ifCondition true: code block1
elseThe code block2
Copy the code

The flow chart is:With both if and else, one code block is executed if the expression is true and another code block is executed if the expression is not. Let’s take a simple example.

age = 3
if age >= 18:
    print('your age is', age)
    print('adult')
else:
    print("your age is", age)
    print('kid')
Copy the code

Determine whether someone is an adult based on the age you enter. If age is greater than or equal to 18, print Adult, otherwise print Kid.

If elif else statement

The if elif else statement is used for multiple conditions. If the condition is not met, the elif condition is executed. If the elif condition is not met, the else expression is executed. The pseudocode is:

ifCondition true: expression AelifCondition true: expression b....elifConditional true: the expression is N -1
elseThe expression of nCopy the code

There can be more than one elif, but elif cannot be used alone. It must be used together with if and else. Note that the code blocks after if,elif, and else must be indent by more than if,elif, and else themselves. The recommended indent is 4 Spaces. All statements in the same code should have the same indentation. Again, to illustrate:

bmi = 80.5 / (1.75 * 1.75)
if bmi < 18.5:
    print('low')
elif 18.5 <= bmi < 25:
    print('normal')
elif 25 <= bmi < 28:
    print('too much')
elif 28 <= bmi < 32:
    print('fat')
else:
    print('Severely obese')
pass
Copy the code

Here’s how to determine whether a person is underweight, normal or obese based on bmi. Pass is a Python keyword that tells the interpreter to skip this point and do nothing.

Use of nested statements

Nested statements are statements that have child judgments in an if or else block of code. As shown in the following example:

Num = 23 if num < 20: print else: if num <= 20 and num < 80: print else: print if num <= 20 and num < 80: printCopy the code

The keyword of the loop

The while loop statement is explained

While is a keyword for the loop. The pseudocode is:

whileConditional expression: code blockCopy the code

It is important to ensure that the loop condition becomes false at some point, otherwise the loop will become an infinite loop, that is, the loop will never end.The flow chart is:The body of the loop is executed if the expression in the while is true, otherwise it is terminated. For example, calculating the sum from 1 to 100 is a classic application loop scenario

sum = 0
n = 1
while n <= 100:
    sum = sum + n
    n = n + 1
print('sum='.sum)
Copy the code

The result is sum= 5050, and the loop ends if n>100, which means that when n>100, the loop breaks out.

Range function

The range function is used to generate a series of numbers. The syntax is:

range(start,end,step)
Copy the code

Start indicates the beginning number (inclusive, optional), end indicates the end number (inclusive, mandatory), and step indicates the step size (optional). The default value is 1.


sum = 0
for x in range(101) :sum = sum + x
print(sum)
print(range(101))
Copy the code

The results are as follows:

5050
range(0, 101)
Copy the code

As you can see, the range() function returns a range object whose contents must be parsed through the for loop. Range (101) The actual run result is range(0,101), default start equals 0, output all numbers in the range 0 to 100, excluding the number 101.

The for loop

The for keyword is used in the introduction of the range function. Here is how to use the for keyword. Its grammatical structure is:

forIteration variableinThe string list | | | | yuan group dictionary collection: the code blockCopy the code

Strings, lists, progenitors, dictionaries, collections can all be iterated with for. The flow chart is:

The for loop is a loop that determines whether there is an item in the sequence based on the IN keyword, fetches the next item if there is, and executes the body of the loop. If not, end the loop.

Range quickly generates an derivation

List derivation

The syntax for a list derivation is

[expression for iterating variable in iterable [if conditional expression]]Copy the code

In this format, the [if conditional expression] is not required and can be used or omitted. Here is an example of a product that outputs lists from 1 to 10:

L = [x * x for x in range(1.11)]
print(L)
Copy the code

This expression is equivalent to

L = []
for x in range(1.11):
    L.append(x * x)
print(L)
Copy the code

The results are as follows:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Copy the code

Let’s get a little more complicated. Here’s the output

print([x for x in range(1.11) if x % 2= =0])

Copy the code

The result is [2, 4, 6, 8, 10] and then a little bit more complicated, using multiple loops, generating the derivation.

d_list = [(x, y) for x in range(5) for y in range(4)]
print(d_list)
Copy the code

The results are as follows:

[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3), (4, 0), (4, 1), (4, 2), (4, 3)]
Copy the code

In the code above, x is the iteration variable (counter) over range(5), so x iterates 5 times, and y is the counter over range(4), so y iterates 4 times. Therefore, the (x,y) expression is iterated 20 times. It is equivalent to a nested expression like the following.

dd_list = []
for x in range(5) :for y in range(4):
        dd_list.append((x, y))
print(dd_list)
Copy the code

Tuple derivation

Tuple comprehensions are similar to list comprehensions in that their syntactic structure is:

(Expression for iterating variable in iterable [if conditional expression])Copy the code

In this format, the [if conditional expression] is not required and can be used or omitted. Here is an example of a product of tuples that output 1 to 10:

d_tuple = (x * x for x in range(1.11))
print(d_tuple)
Copy the code

The results are as follows:

<generator object <genexpr> at 0x103322e08>

Copy the code

As you can see from the execution results above, the result generated using a tuple derivation is not a tuple, but a generator object. Using the tuple() function, you can directly convert a generator object into a tuple. Such as:

d_tuple = (x * x for x in range(1, 11))
print(tuple(d_tuple))
Copy the code

The output is (1, 4, 9, 16, 25, 36, 49, 64, 81, 100).

Dictionary derivation

The grammatical structure of a dictionary derivation is:

{expression for iterating variable in iterable [if conditional expression]}Copy the code

[if condition expression] can be used or omitted. Here’s an example:

key_list = ['Name: Non Fly Brother'.'age: 18'.'Hobby: Blogging']
test_dict = {key.split(':') [0]: key.split(':') [1] for key in key_list}
print(test_dict)
Copy the code

The results are as follows:

{' Hobby ': 'blogging ',' age ': '18', 'name ':' Code nongfei '}Copy the code

Nested loop

Nested loops are loops within loops, and the classic is bubble sort. Bubble sort compares the right and left adjacent digits at a time, and switches the positions of the two digits if the first digit is larger than the next. Here’s a demonstration:

test_list = [12.3.1.13.10.5.9]
for i in range(len(test_list)):
    for j in range(len(test_list) - i - 1) :if test_list[j] > test_list[j + 1]:
            tmp = test_list[j]
            test_list[j] = test_list[j + 1]
            test_list[j + 1] = tmp
    print('{0} loop results in ='..format(str(i)), test_list)
print(The final result is equal to 0., test_list)
Copy the code

The results are as follows:

The result after the 0 cycle is = [3, 1, 12, 10, 5, 9, 13] The result after the 1 cycle is = [1, 3, 10, 5, 9, 12, 13] And the result after the 2 cycle is = [1, 3, 5, 9, 10, 12, 13] After the third cycle, the result is = [1, 3, 5, 9, 10, 12, 13] After the fourth cycle, the result is = [1, 3, 5, 9, 10, 12, 13] After the fifth cycle, the result is = [1, 3, 5, 9, 10, 12, 13, 13] The result after the sixth cycle is = [1, 3, 5, 9, 10, 12, 13] The final result is = [1, 3, 5, 9, 10, 12, 13]Copy the code

As you can see, the outer loop is responsible for the number of times bubble sort takes place, while the inner loop is responsible for comparing two adjacent elements in the list and adjusting the order so that the smaller element is placed first.

Jump out of the loop

There are two key words to break out of the loop, a continue statement and a break statement.

  1. The continue statement is used to jump out of executing the rest of the loop body and execute the next loop.
n = 0
while n <= 5:
    n = n + 1
    if n == 3:
        continue
    print(n)
Copy the code

The result of the run is:

One, two, four, five, sixCopy the code

You can see that the number 3 is skipped. 2. The break statement is used to completely terminate the current loop. Note that if the loop is nested, only the loop that uses break can be broken. Or take the previous bubble sort as an example!

for i in range(len(test_list)):
    for j in range(len(test_list) - i - 1) :if test_list[j] > test_list[j + 1]:
            test_list[j], test_list[j + 1] = test_list[j + 1], test_list[j]
        if j == 2:
            print('Inner loop break')
            break
    if i == 3:
        print('Outer loop break')
        break
Copy the code

The results are as follows:

Inner loop break Inner loop break Outer loop breakCopy the code

It can be seen that the break of the inner loop does not affect the outer loop. That is, break only breaks out of the current loop.

conclusion

This article briefly introduces the keywords for flow control in Python: if, elif, and else. The loop structure is the while and for keywords. The syntax is simple.

I am Mynongfei and thank you again for reading this article. The whole network with the same name [code nongfei brother]. Thank you again for reading this article.