Hello, I’m Brother Nongfei, thank you for reading this article, welcome one key three.


This article focuses on the use of process-control keywords in Python, including if, else,for,while, and so on


Full of dry goods, suggested collection, need to see often. 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 + a data structure. This is true of any program. Having spent several pages covering the various data structures in Python, this article continues with a look at flow control. Data structures are used to store data, and processes are used to control the operation of the system.

Process control

Flow control has three structures, one is sequential structure, one is selective (branch) structure, and one is circular structure. Sequential structure: The program executes the code from beginning to end, without repeating or skipping any line of code. One step at a time is what it means. Selecting (branching) structure: this is where the program executes different code based on different conditions, such as determining whether someone is an adult based on their age. Loop structure: is to let the program loop through a certain piece of code. The sequential flow will not be described here.

Select the structure (if,else) :

If statement

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

If condition is true: code block

Executes the block if the condition after the if is true. Otherwise, the execution of the code is skipped.

The flow chart is as follows:



That is, if only, the block executes if the expression holds, and terminates if it does not.

Here is a simple example: print a if a==1, otherwise skip the statement.

a = 1
if a == 1:
    print(a)

If the else statement

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

If condition true: block 1 else block 2

The flow chart is as follows:



If and else are used together, one block of code is executed if the expression is true, and another if the expression is not true.

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')

Determine whether someone is an adult based on the age entered. If age is 18 or greater, print adult; otherwise, print kid.

If elif else

If elif else is not satisfied, then elif is executed. If elif is not satisfied, then elif is executed. If elif is not satisfied, then elelse is executed. The pseudocode is:

If condition is true: expression a elif condition is true: expression b.... The elif condition is true: the expression is n-1 else expression n

There can be more than one elif, but elif cannot be used alone. It must be used with an if and an else. Note that the block after the if,elif, and else code must be indented, and the amount of indentation is greater than that of the if,elif, and else code itself. The recommended amount of indentation is 4 Spaces. All statements in the same code should have the same indentation. Again, an example:

Print (' normal ') elif 25 <= BMI < 28: print(' normal ') elif 25 <= BMI < 28: Print (' obese ') elif 28 <= BMI < 32: print(' obese ') else: print(' obese ') pass

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

Use of nested statements

A nested statement is a block of if or else code in which there are subjudgments. As shown in the following example:

Num = 23 if num < 20: print(' num ') else: print(' print ')

Keyword for the loop

While loop statement elaboration

While is a keyword used as a loop. The pseudocode is:

While condition expression: Code block

Make sure that the loop condition becomes false at some point, otherwise the loop becomes an infinite loop, meaning that the loop cannot be finished.The flow chart is as follows:



The body of the loop is executed if the expression in the while holds, otherwise it terminates.

For example, calculating the sum from 1 to 100 is a classic case of using loops

sum = 0
n = 1
while n <= 100:
    sum = sum + n
    n = n + 1
print('sum=', sum)

The result is sum= 5050. The end condition of the loop is n>100, which means that n>100 will break the loop.

Range function

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

range(start,end,step)

Start refers to the number at the beginning (included, optional), end to the number at the end (not included, required), step length (optional), the default is 1.


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

The running result is:

5050
range(0, 101)

You can see that the range() function returns a range object that must be parsed through the for loop to output its contents. The actual result of running range(101) is range(0,101). Default start is equal to 0. It will output all the numbers in the range from 0 to 100, excluding the number 101.

The for loop

The for keyword was used in the introduction to the range function. Here’s how to use it. The grammatical structure is:

For iteration variables in the string list | | | | yuan group dictionary collection: the code block

Strings, lists, primitives, dictionaries, collections can all be iterated over using for. The flow chart is as follows:

The “for” loop first determines if there is an item in the sequence based on the “in” keyword. If there is, the next item is removed and the body of the loop is executed. If not, the loop is terminated.

Range generates derivations quickly

Tabular derivation

The syntactic format of the list derivation is

[Expression for iterates variable in iterable object [if conditional expression]]

In this format, the [if condition] is not required and can be used or omitted. Here is an example of the product of a list that outputs 1 through 10:

L = [x * x for x in range(1, 11)]
print(L)

This expression is equivalent to

L = []
for x in range(1, 11):
    L.append(x * x)
print(L)

The running result is:

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

Let’s make it a little more complicated. Here’s the output

print([x for x in range(1, 11) if x % 2 == 0])

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

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

The running result is:

[(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)]

In the above code, x is the iteration variable (counter) traversing range(5), so this x can iterate 5 times, and y is the counter traversing range(4), so this y can iterate 4 times. Thus, the (x,y) expression is iterated 20 times in total. It corresponds to a nested expression like this.

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

Tuple derivation

The tuple derivation is similar to the list derivation in that it has the syntax structure:

(Expression for iterates variable in iterable object [if conditional expression])

In this format, the [if condition] is not required and can be used or omitted. Here is an example of printing the product of tuples from 1 to 10:

d_tuple = (x * x for x in range(1, 11))
print(d_tuple)

The running result is:

<generator object <genexpr> at 0x103322e08>

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

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

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

Dictionary derivation

The grammatical structure of the lexicographical derivation is:

{expression for iterable variable in iterable object [if conditional expression]}

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

Key_list = [' s name, code farmer flying elder brother ', 'age: 18', 'hobbies: blogging] test_dict = {key. The split (' :') [0] : key.split(':')[1] for key in key_list} print(test_dict)

The running result is:

{' Hobbies ': 'blog ',' Age ': '18', 'Name ':' Nongfei Brother '}

Nested loop

Nested loops are loops within loops, and the classic is bubble sort. Bubble Sort compares the left and right adjacent numbers each time, swapping the positions of the two numbers if the first number is larger than the next. Here’s how it works:

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('.format(STR (I)) '), Test_list) print(' test_list =', test_list)

The running result is:

The result after loop 0 is = [3, 1, 12, 10, 5, 9, 9, 13] The result after loop 1 is = [1, 3, 5, 9, 10, 12, The result after the third cycle is = [1, 3, 5, 9, 10, 12, 13] The result after the fourth cycle is = [1, 3, 5, 9, 10, 12, 13] = [1, 3, 5, 9, 10, 12, 13] = [1, 3, 5, 9, 10, 12, 13]

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

Jump out of the loop

The two keywords that break out of the loop are the continue statement and the break.

  1. The continue statement is used to break out of the remaining code in the body of the loop to execute the next loop.
n = 0
while n <= 5:
    n = n + 1
    if n == 3:
        continue
    print(n)

The result of the run is:

One, two, four, five, six

You can see the number 3 is skipped.

  1. The break statement is used to completely terminate the current loop. Note that if the loop is nested, only the loop that uses a break can be interrupted. Take the bubble sort to give 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 + 1] = test_list[j + 1], test_list[j] if j == 2: print(' break') break if I == 2: print(' break') break if I == 3: Print (' outer loop break') break

The running result is:

Inner circle break inner circle break inner circle break outer circle break inner circle break

It can be seen that the break of the inner loop does not affect the outer loop. This means that the break will only break out of the current loop.

conclusion

This article introduces a few keywords for flow control in Python. If you choose a structure, they are: if, elif, and else. Loops are the keywords while and for. The syntax is simple.

I am Brother Nongfei. Thank you again for reading this article.


The whole network of the same name [code farm fly elder brother]. Enjoy the joy of sharing every single step, every single mile


I am Brother Nongfei. Thank you again for reading this article.