Table of contents
1. Python3 conditional control
1. The general form of an if statement in Python is as follows:
4. The following are commonly used operation operators in if:
5. The high_low.py file demonstrates the comparison operation of numbers:
1. Python 3.10 adds match...case condition judgment, no need to use a series of if-else to judge.
3. The grammar format is as follows:
5. A case can also set multiple matching conditions, and the conditions are separated by |
(1) The loop statements in Python include for and while.
(2) The control structure diagram of the Python loop statement is as follows:
1. The general form of the while statement in Python:
2. The execution flow chart is as follows:
4. The following example uses while to calculate the sum from 1 to 100:
6. The while loop uses the else statement
1. The Python for loop can traverse any iterable object, such as a list or a string.
2. The general format of a for loop is as follows:
4. Example of Python for loop:
5. It can also be used to print each character in a string:
6. Integer range values can be used with the range() function:
2. You can also use range() to specify the value of the interval:
6. You can also use the range() function to create a list:
(6) break and continue statements and the else clause in the loop
1. Break execution flow chart:
2. Continue execution flow chart:
3. While statement code execution process:
4. For statement code execution process:
1. Python pass is an empty statement to maintain the integrity of the program structure.
4. The following example executes the pass statement block when the letter is o:
1. Python3 conditional control
(1) A Python conditional statement is a code block that is determined to be executed by the execution result (True or False) of one or more statements.
You can simply understand the execution process of the conditional statement through the following figure:
Code execution process:
(2) if statement
1. The general form of an if statement in Python is as follows:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- If "condition_1" is True, the "statement_block_1" block statement will be executed
- If "condition_1" is False, "condition_2" will be judged
- If "condition_2" is True, the "statement_block_2" block statement will be executed
- If "condition_2" is False, the "statement_block_3" block statement will be executed
In Python, elif is used instead of else if , so the keywords of the if statement are: if – elif – else .
2. Note:
① A colon: should be used after each condition, indicating that the following is the statement block to be executed after the condition is met.
② Use indentation to divide statement blocks, and statements with the same indentation number form a statement block together.
③ There is no switch...case statement in Python, but match...case is added in Python3.10 version, and the function is similar, see below for details.
Gif demo:
3. Examples:
①The following is a simple if example:
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - if expression condition is true")
print (var1)
var2 = 0
if var2:
print ("2 - if expression condition is true")
print (var2)
print ("Good bye!")
Execute the above code, the output is:
1 - if expression condition is true 100 Good bye!
From the result, we can see that because the variable var2 is 0, the corresponding if statement is not executed.
②The following example demonstrates the calculation and judgment of a dog's age:
#!/usr/bin/python3
age = int(input("Please enter the age of your dog: "))
print("")
if age <= 0:
print("You are kidding me!")
elif age == 1:
print("Equivalent to a 14-year-old.")
elif age == 2:
print("Equivalent to a 22-year-old person.")
elif age > 2:
human = 22 + (age -2)*5
print("corresponding to human age: ", human)
### Exit Prompt
input("Click the enter key to exit")
Save the above script in the dog.py file and execute the script:
$ python3 dog.py Please enter your dog's age: 1 Equivalent to a 14-year-old. Click the enter key to exit
4. The following are commonly used operation operators in if:
operator | describe |
---|---|
< |
less than |
<= |
less than or equal to |
> |
more than the |
>= |
greater than or equal to |
== |
equals, compares whether two values are equal |
!= |
not equal to |
Example:
#!/usr/bin/python3
# The program demonstrates the == operator
# use numbers
print(5 == 6)
# use variables
x = 5
y = 8
print(x == y)
The output of the above example:
False False
5. The high_low.py file demonstrates the comparison operation of numbers:
Example:
#!/usr/bin/python3
# This example demonstrates the number guessing game
number = 7
guess = -1
print("Number guessing game!")
while guess != number:
guess = int(input("Please enter the number you guessed:"))
if guess == number:
print("Congratulations, you guessed it!")
elif guess < number:
print("The guessed number is too small...")
elif guess > number:
print("The guessed number is too big...")
Execute the above script, the example output is as follows:
$ python3 high_low.py Number Guessing Game! Please enter the number you guessed: 1 Guess the number is small... Please enter the number you guessed: 9 Guess the number is big... Please enter the number you guessed: 7 Congratulations, you guessed it!
(3) if nested
1. In the nested if statement, you can put the if...elif...else structure in another if...elif...else structure.
if expression 1: statement if expression 2: statement elif expression 3: statement else: statement elif expression 4: statement else: statement
2. Examples
# !/usr/bin/python3
num=int(input("Enter a number:"))
if num%2==0:
if num%3==0:
print ("The number you entered is divisible by 2 and 3")
else:
print ("The number you entered is divisible by 2, but not by 3")
else:
if num%3==0:
print ("The number you entered is divisible by 3, but not by 2")
else:
print ("The number you entered is not divisible by 2 and 3")
Save the above program to the test_if.py file, and the output after execution is:
$ python3 test.py Enter a number: 6 The number you entered is divisible by 2 and 3
(4) match...case
1. Python 3.10 adds match...case condition judgment, no need to use a series of if-else to judge.
2. The object after the match will be matched with the content after the case in turn. If the match is successful, the matched expression will be executed, otherwise it will be skipped directly. _ can match everything.
3. The grammar format is as follows:
match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard>
4. case _: is similar to default: in C and Java. When other cases cannot be matched, match this one, and it is guaranteed that the match will always be successful.
Example:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
mystatus=400
print(http_error(400))
The above is an example of outputting the HTTP status code, and the output result is:
Bad request
5. A case can also set multiple matching conditions, and the conditions are separated by |
For example:
... case 401|403|404: return "Not allowed"
2. Python3 loop statement
(1) The loop statements in Python include for and while.
(2) The control structure diagram of the Python loop statement is as follows:
(3) while loop
1. The general form of the while statement in Python:
while condition: Execute statements...
2. The execution flow chart is as follows:
3. Execute the Gif demo:
Also pay attention to colons and indentation. Also, there is no do..while loop in Python.
4. The following example uses while to calculate the sum from 1 to 100:
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("The sum of 1 to %d is: %d" % (n,sum))
The execution results are as follows:
The sum of 1 to 100 is: 5050
5. Infinite loop
We can achieve an infinite loop by setting the conditional expression to never be false
Examples are as follows:
#!/usr/bin/python3
was = 1
while var == 1 : # expression is always true
num = int(input("Enter a number:"))
print ("The number you entered is: ", num)
print ("Good bye!")
Execute the above script, the output is as follows:
Enter a number: 5 The number you entered is: 5 Enter a number :
You can use CTRL+C to exit the current infinite loop.
Infinite loops are useful for real-time client requests on the server.
6. The while loop uses the else statement
① If the conditional statement after while is false, execute the statement block of else.
The syntax format is as follows:
while <expr>: <statement(s)> else: <additional_statement(s)>
The statement block statement(s) is executed if the conditional statement of expr is true, and additional_statement(s) is executed if it is false.
②Cycle output numbers and judge the size:
Example:
#!/usr/bin/python3
count = 0
while count < 5:
print (count, "less than 5")
count = count + 1
else:
print (count, "greater than or equal to 5")
Execute the above script, the output is as follows:
0 less than 5 1 less than 5 2 less than 5 3 less than 5 4 less than 5 5 greater than or equal to 5
7. Simple sentence group
Similar to the syntax of the if statement, if you have only one statement in the body of the while loop, you can write that statement on the same line as the while, as follows:
#!/usr/bin/python
flag = 1
while (flag):
print ('Welcome to the rookie tutorial!')
print ("Good bye!")
Note: You can use CTRL+C to interrupt the infinite loop above.
Execute the above script, the output is as follows:
Welcome to the rookie tutorial! Welcome to the rookie tutorial! Welcome to the rookie tutorial! Welcome to the rookie tutorial! Welcome to the rookie tutorial! ……
(4) for statement
1. The Python for loop can traverse any iterable object, such as a list or a string.
2. The general format of a for loop is as follows:
for <variable> in <sequence>:
<statements>
else:
<statements>
3. Flow chart:
4. Example of Python for loop:
#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
print(site)
The output of the above code execution is:
Baidu Google Runob Taobao
5. It can also be used to print each character in a string:
Example:
#!/usr/bin/python3
word = 'runoob'
for letter in word:
print(letter)
The output of the above code execution is:
r u n o o b
6. Integer range values can be used with the range() function:
#!/usr/bin/python3
# All numbers from 1 to 5:
for number in range(1, 6):
print(number)
The output of the above code execution is:
1 2 3 4 5
7、for...else
①In Python, the for...else statement is used to execute a piece of code after the loop ends.
②The grammar format is as follows:
for item in iterable: # loop body else: # Code to execute after the loop ends
③When the loop is executed (that is, after traversing all the elements in the iterable), the code in the else clause will be executed. If a break statement is encountered during the loop, the loop will be interrupted, and the else clause will not be executed at this time.
Example:
for x in range(6):
print(x)
else:
print("Finally finished!")
After executing the script, the output is:
0 1 2 3 4 5 Finally finished!
④The break statement is used in the following for example, the break statement is used to jump out of the current loop body, and the else clause will not be executed:
Example:
#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("Noob Tutorial!")
break
print("loop data" + site)
else:
print("No cyclic data!")
print("Complete loop!")
After executing the script, it will jump out of the loop body when looping to "Runoob":
Cyclic DataBaidu Cycle Data Google Rookie Tutorial! Complete the cycle!
(5) range() function
1. If you need to traverse a sequence of numbers, you can use the built-in range() function. It generates arrays such as:
>>>for i in range(5):
... print(i)
...
0
1
2
3
4
2. You can also use range() to specify the value of the interval:
Example:
>>>for i in range(5,9) :
print(i)
5
6
7
8
>>>
3. You can also make range() start with a specified number and specify a different increment (it can even be a negative number, sometimes this is also called a 'step size'):
Example:
>>>for i in range(0, 10, 3) :
print(i)
0
3
6
9
>>>
4. Negative numbers:
Example:
>>>for i in range(-10, -100, -30) :
print(i)
-10
-40
-70
>>>
5. You can combine the range() and len() functions to traverse the index of a sequence, as shown below:
Example:
>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Love
3 Taobao
4 QQ
>>>
6. You can also use the range() function to create a list:
Example:
>>>list(range(5))
[0, 1, 2, 3, 4]
>>>
(6) break and continue statements and the else clause in the loop
1. Break execution flow chart:
2. Continue execution flow chart:
3. While statement code execution process:
4. For statement code execution process:
The break statement can jump out of the loop body of for and while. If you terminate from a for or while loop, any corresponding loop else blocks will not execute.
The continue statement is used to tell Python to skip the remaining statements in the current loop block and continue to the next loop.
5. Examples
① Use break in while:
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('End of loop.')
The output is:
4 3 The loop ends.
②Use continue in while:
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('End of loop.')
The output is:
4 3 1 0 The loop ends.
③ More examples are as follows:
#!/usr/bin/python3
for letter in 'Runoob': # first instance
if letter == 'b':
break
print ('The current letter is:', letter)
var = 10 # second instance
while var > 0:
print ('The current variable value is:', var)
var = var -1
if var == 5:
break
print ("Good bye!")
The output of executing the above script is:
Current letter is: R Current letter is: u Current letter is: n Current letter is: o Current letter is: o Current variable value: 10 Current variable value: 9 Current variable value: 8 Current variable value: 7 Current variable value: 6 Good bye!
④The following example loops the string Runoob, and skips the output when encountering the letter o:
Example:
#!/usr/bin/python3
for letter in 'Runoob': # first instance
if letter == 'o': # skip output when the letter is o
continue
print ('current letter:', letter)
var = 10 # second instance
while var > 0:
var = var -1
if var == 5: # Skip output when the variable is 5
continue
print ('Current variable value:', var)
print ("Good bye!")
The output of executing the above script is:
Current letter: R Current letter: u Current letter: n Current letter: b Current variable value: 9 Current variable value: 8 Current variable value: 7 Current variable value: 6 Current variable value: 4 Current variable value: 3 Current variable value: 2 Current variable value: 1 Current variable value: 0 Good bye!
⑤The loop statement can have an else clause, which is executed when the list is exhausted (for loop) or the condition becomes false (while loop) causes the loop to terminate, but it is not executed when the loop is terminated by break.
The following example is used to query the cycle example of prime number:
#!/usr/bin/python3
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equal to', x, '*', n//x)
break
else:
# No element found in the loop
print(n, 'is a prime number')
The output of executing the above script is:
2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
(7) pass statement
1. Python pass is an empty statement to maintain the integrity of the program structure.
2. pass does not do anything, and is generally used as a placeholder statement, as shown in the following example
>>>while True:
... pass # Wait for keyboard interrupt (Ctrl+C)
3. The smallest class:
Example:
>>>class MyEmptyClass:
... pass
4. The following example executes the pass statement block when the letter is o:
#!/usr/bin/python3
for letter in 'Runoob':
if letter == 'o':
pass
print('execute pass block')
print ('current letter:', letter)
print ("Good bye!")
The output of executing the above script is:
Current letter: R Current letter: u Current letter: n execute pass block Current letter: o execute pass block Current letter: o Current letter: b Good bye!