Getting started with Python zero Basics

6, Process control

6.1 program structure

When a computer solves a specific problem, there are three main situations: sequential execution of all statements, selective execution of partial statements and circular execution of partial statements. The three basic structures in corresponding programming are sequence structure, selection structure and cycle structure. The execution flow chart of these three structures is shown in the figure below:

The first figure is the flow chart of sequential structure, and the written statements are executed in sequence according to the writing order; The second figure is the flow chart of the selection structure
, it mainly selects and executes different statements according to the results of conditional statements; The third figure is the flow chart of circular structure, which is repeated under certain conditions
The flow structure of executing a certain program, in which the repeatedly executed statement is called the loop body, and the judgment condition that determines whether the loop is terminated is called the loop condition.

6.2 selection statement

In life, we always have to make many choices, and so does the program.
For example, if you pass the English test with a score greater than 60, the lottery number you buy is equal to the published lottery prize number, and you will win the prize. Similar to this judgment is the selection statement in the program, also known as conditional statement, that is, different code fragments are selected and executed according to conditions. There are three main forms of selection statements in Python: if statement, if... else statement and if... elif... else multi branch statement.

Note: in other languages (such as c, c + +, java, etc.), selection statements also include switch statements, which can also realize multiple selection. However, in python, there is no switch statement, so when realizing the function of multiple selection, you can only use if... else statement and if... elif... else multi branch statement or if statement nesting.

6.2.1 simplest if statement

Python uses the if reserved word to form a selection statement. Its simplest syntax is as follows:
if expression:
Statement block
The expression can be a simple Boolean value or variable, or a comparison expression or logical expression (for example, a > b and a! = C),
If the expression is true, execute "statement block"; If the expression is false, skip the "statement block" and continue to execute the following statements, this form of if
The sentence is equivalent to "if... Then..." in Chinese, and its flow chart is as follows:

In the expression of conditional statement, the operation operators are often required, as shown in the following table:

(1) If you have purchased a lottery ticket and the winning number is announced, the number is "432678", then you can use the if statement to judge whether you will win the lottery.

number = int(input("Please enter your 6-digit ticket number:"))
if number == 432678:
    print(number, "You have won the prize. Please come and receive the prize quickly!")
if number != 432678:
    print(number, "You didn't win this award!")
Please enter your 6-digit ticket number: 112345
112345 You didn't win this award!

(2) In actual commodity sales, it is often necessary to classify commodity price and sales volume. For example, commodities with commodity sales greater than or equal to 100 can be represented by A. The implementation method with if statement is as follows:

data = 105
if data >= 100:
    print(data, "This item is A Class goods!")
105 This item is A Class goods!

If the daily sales volume of goods is less than 100, it can be represented by B. The implementation method with if statement is as follows:

data = 65
if data < 100:
    print(data, "This item is B Class goods!")
65 This item is B Class goods!

Note: when using an IF statement, if there is only one statement, the statement block can be written directly to the right of ":", as follows:
if a>b: max=a
However, for the readability of the program code, it is recommended not to write this.

6.2.2 if... else statement

Python provides if... else statements to solve similar problems. The syntax format is as follows:
if expression:
Statement block 1
else:
Statement block 2
When using the if... Else statement, the expression can be a simple Boolean value or variable, or a comparison expression or logical expression. If the conditions are met, the statement block after if is executed; otherwise, the statement block after else is executed. This form of selection statement is equivalent to the associated words in Chinese
"If... Otherwise...", the flow chart is shown in the following figure:

Let's continue with the lottery example:

number = int(input("Please enter your 6-digit ticket number:"))
if number == 432678:
    print(number, "You have won the prize. Please come and receive the prize quickly!")
else:
    print(number, "You didn't win this award!")
Please enter your 6-digit ticket number: 432678
432678 You have won the prize. Please come and receive the prize quickly!

Examples of commodity sales are as follows:

data = 105
if data >= 100:
    print(data, "This item is A Class goods!")
else:
    print(data, "This item is B Class goods!")
105 This item is A Class goods!

Tip: if... else statements can be simplified using conditional expressions, as shown in the following code:
a = -9
if a>0:
b = a
else:
b = -a
print(b)
The above code can be abbreviated as:
a = -9
b = a if a>0 else -a
print(b)
The advantage of using conditional expressions is that they make the code concise and have a return value.

6.2.3 if... elif... else statement

The syntax format of if... elif... else statement is as follows:
if expression 1:
Statement block 1
elif expression 2:
Statement block 2
elif expression 3:
Statement block 3
...
else:
Statement block n

When using the if... Elif... Else statement, the expression can be a simple Boolean value or variable, or a comparison expression or logical expression. If the expression is true, execute the statement; If the expression is false, skip the statement and judge the next elif. The statement in else will be executed only when all expressions are false. The flow chart of if... Elif... Else statement is as follows:

Insert figure 6-6

Here is a code example:

number = int(input("Please enter the 7-day sales volume of the product:"))
if number >= 1000:
    print("The 7-day sales volume of this commodity is A!!")
elif number >= 500:
    print("The 7-day sales volume of this commodity is B!!")
elif number >= 300:
    print("The 7-day sales volume of this commodity is C!!")
else:
    print("The 7-day sales volume of this commodity is D!!")
Please enter the 7-day sales volume of goods: 200
 The 7-day sales volume of this commodity is D!!

Note: both if and elif need to judge whether the expression is true or false, while else does not need to judge; In addition, elif and else must be used together with if and cannot be used alone

6.2.4 nesting of if statements

Three forms of if selection statements were introduced earlier. These three forms of selection statements can be nested with each other.
The simplest if statement is nested with if... else statements in the following form:
if expression 1:
if expression 2:
Statement block 1
else:
Statement block 2
Nest the if... else statement in the if... else statement. The format is as follows:
if expression 1:
if expression 2:
Statement block 1
else:
Statement block 2
else:
if expression 3:
Statement block 3
else:
Statement block 1
Here is a code example:

number = int(input("Please enter the 7-day sales volume of the product:"))
if number >= 1000:
    print("The 7-day sales volume of this commodity is A!!")
else:
    if number >= 500:
        print("The 7-day sales volume of this commodity is B!!")
    else:
        if number >= 300:
            print("The 7-day sales volume of this commodity is C!!")
        else:
            print("The 7-day sales volume of this commodity is D!!")
Please enter the 7-day sales volume of goods: 555
 The 7-day sales volume of this commodity is B!!

Note: if selection statements can have a variety of nesting methods. When developing programs, you can choose the appropriate nesting method according to your own needs, but you must strictly control the indentation of code blocks at different levels.

6.3 using and join conditional statements

In practical work, we often encounter the need to meet two or more conditions at the same time to execute the statement block after if, as shown in the following figure:

The following code example is as follows:

age = int(input("Please enter your age:"))
if age >= 18 and age <= 70:
    print("You can apply for a small car driver's license!")
Please enter your age: 20
 You can apply for a small car driver's license!
# In fact, the above effect can be achieved by nesting only if statements without and statements
age = int(input("Please enter your age:"))
if age >= 18:
    if age <= 70:
        print("You can apply for a small car driver's license!")
Please enter your age: 22
 You can apply for a small car driver's license!

Take another example code:

print("Now there are things that don't know their number, two out of three, three out of five, and two out of seven,Ask geometry?")
number = int(input("Please enter the number you think is qualified:"))
if number%3 == 2 and number%5 == 3 and number%7 == 2:
    print(number, "Eligible: two out of three, three out of five, two out of seven")
Now there are things that don't know their number, two out of three, three out of five, and two out of seven,Ask geometry?
Please enter the number you think is qualified: 23
23 Eligible: two out of three, three out of five, two out of seven

Note: the above code is not perfect. You can try to improve it!

6.4 using or join conditional statements

Sometimes, as long as one of two or more conditions is required, the statement block after if can be executed, as shown in the following figure:

Or is a Python logical operator. You can use or to judge the content of multiple conditions in conditions. As long as one condition is met, the statement block after if can be executed. For example, commodities with daily sales of less than 10 and commodities with daily sales of more than 100 are listed as key commodities. Use or to realize the judgment of two conditions, input daily sales volume < 10 or input daily sales volume > 100, and use print to output "this commodity is a commodity of key concern", the code is as follows:

sales = int(input("Please enter daily sales volume"))
if sales < 10 or sales > 0:
    print("This product is a focus product")
Please enter daily sales volume of goods 1
 This product is a focus product
# The above effect can also be achieved without or statement and only two simple if statements. The code is as follows
sales = int(input("Please enter daily sales volume"))
if sales < 10:
    print("This product is a focus product")
Please enter daily sales volume of goods 1
 This product is a focus product

6.5 using the not statement

Not statement is used to judge the program in development. Not is a logical judgment word, which is used for Boolean True and False. Not is used in conjunction with the logical judgment sentence if, which means that when the expression after not is False, the statement after the colon is executed. The example code is as follows:

data = None
if not data:
    print("You lost!")
else:
    print("You win!")
You lost!

The output of this program is "You lost!". Note: when the expression after not is False, the statement after the colon is executed, so the value of the expression after not is particularly critical.
If the code is changed as follows:
data = "a"
The output result is "You win!" Note: in python, False, None, empty string, empty list, empty dictionary and empty tuple are equivalent to False.
"if x is not None" is the best way to write. It is not only clear, but also free of errors. Please try to use this way. The premise of using "if not x" is that it must be clear that when x is equal to None, False, empty string, 0, empty list, empty dictionary and empty tuple, it will not affect the judgment.

In python, to determine whether a specific value exists in the list, you can use the keyword in: to determine whether a specific value is not in the list, you can use the keyword not in. The example code is as follows:

a = input("Please enter a 1-digit password")
b = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if a not in b:
    print("illegal input")
Please enter 1 digit password 00
 illegal input

epilogue

Today, I will continue the basic content of python in the previous chapter! Continue the study of data analysis pandas library!

Keywords: Python Programming

Added by ronnimallouk on Fri, 21 Jan 2022 12:06:24 +0200