Conditional control and loop statements

Python3 condition control

The Python conditional statement determines the code block to be executed based on 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:
Insert picture description here
Code execution process:

Insert picture description here

if statement

The general form of the 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 block statement "statement_block_2" will be executed
  • If "condition_2" is False, the "statement_block_3" block statement will be executed

Python uses elif instead of else if, so the keyword of the if statement is: if-elif-else.

Note:
1. Use a colon after each condition: to indicate that the next statement block is to be executed after the condition is met.
2. Use indentation to divide sentence blocks, and sentences with the same indentation number together form a sentence block.
3. There is no switch-case statement in Python.

Demo:

a=1
while a < 7:
if (a % 2 == 0):
	print(a,"is even")
else:
	print(a,"is odd")
a += 1

if instance:

#!/usr/bin/python3
 
var1 = 100
if var1:
    print ("1 - if 表达式条件为 true")
    print (var1)
 
var2 = 0
if var2:
    print ("2 - if 表达式条件为 true")
    print (var2)
print ("Good bye!")

Execute the above code, the output result is:

1 - if 表达式条件为 true
100
Good bye!

From the result, we can see that since the variable var2 is 0, the statement in the corresponding if is not executed.

The following example demonstrates the judgment of the dog's age calculation:

#!/usr/bin/python3
 
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
    print("你是在逗我吧!")
elif age == 1:
    print("相当于 14 岁的人。")
elif age == 2:
    print("相当于 22 岁的人。")
elif age > 2:
    human = 22 + (age -2)*5
    print("对应人类年龄: ", human)
 
### 退出提示
input("点击 enter 键退出")

Save the above script in the dog.py file and execute the script:

$ python3 dog.py 
请输入你家狗狗的年龄: 1

相当于 14 岁的人。
点击 enter 键退出

The following operators are commonly used in if:
Insert picture description here

#!/usr/bin/python3
 
# 程序演示了 == 操作符
# 使用数字
print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)

The output of the above example:

False
False

The high_low.py file demonstrates numerical comparison operations:

#!/usr/bin/python3 
 
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
    guess = int(input("请输入你猜的数字:"))
 
    if guess == number:
        print("恭喜,你猜对了!")
    elif guess < number:
        print("猜的数字小了...")
    elif guess > number:
        print("猜的数字大了...")

Execute the above script, the output result of the example is as follows:

$ python3 high_low.py 
数字猜谜游戏!
请输入你猜的数字:1
猜的数字小了...
请输入你猜的数字:9
猜的数字大了...
请输入你猜的数字:7
恭喜,你猜对了!

if nested

In the nested if statement, you can put the if...elif...else structure in another if...elif...else structure.

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句
# !/usr/bin/python3
 
num=int(input("输入一个数字:"))
if num%2==0:
    if num%3==0:
        print ("你输入的数字可以整除 2 和 3")
    else:
        print ("你输入的数字可以整除 2,但不能整除 3")
else:
    if num%3==0:
        print ("你输入的数字可以整除 3,但不能整除 2")
    else:
        print  ("你输入的数字不能整除 2 和 3")

Save the above program to the test_if.py file, and the output after execution is:

$ python3 test.py 
输入一个数字:6
你输入的数字可以整除 23

Python3 loop statement

Loop statements include for and while.
The control structure diagram of Python loop statement is as follows:
Insert picture description here

while loop

The general form of the while statement in Python:

while 判断条件(condition):
    执行语句(statements)……

The execution flow chart is as follows:
Insert picture description here
Perform demonstration:

a=1
while a < 10:
	print(a)
a += 2

Also need to pay attention to the colon and indentation. In addition, there is no do...while loop in Python.

The following example uses while to calculate the sum of 1 to 100:

#!/usr/bin/env python3
 
n = 100
 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 到 %d 之和为: %d" % (n,sum))

The results are as follows:

1100 之和为: 5050

Infinite loop Infinite loop
can be realized by setting the conditional expression to never be false. Examples are as follows:

#!/usr/bin/python3
 
var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)
 
print ("Good bye!")

Execute the above script, the output result is as follows:

输入一个数字  :5
你输入的数字是:  5
输入一个数字  :

You can use CTRL+C to exit the current infinite loop.
The else statement is used
in the while loop . The else statement block is executed when the conditional statement is false while… else.
The syntax format is as follows:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

Output numbers in a loop and determine the size:

#!/usr/bin/python3
 
count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

Execute the above script, the output result is as follows:

0  小于 5
1  小于 5
2  小于 5
3  小于 5
4  小于 5
5  大于或等于 5

Simple statement group
The syntax is similar to if statement. If there is only one statement in the body of the while loop, you can write the statement and while on the same line, as shown below:

#!/usr/bin/python
 
flag = 1
 
while (flag): print ('欢迎访问!')
 
print ("Good bye!")

***Note: You can use CTRL+C to interrupt the infinite loop above.
Execute the above script, the output result is as follows:

欢迎访问!
欢迎访问!
欢迎访问!
欢迎访问!
欢迎访问!
……

for statement

The Python for loop can traverse any sequence of items, such as a list or a string.
The general format of a for loop is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

Flow chart:
Insert picture description here
Python for loop example:

>>>languages = ["C", "C++", "Perl", "Python"] 
>>> for x in languages:
...     print (x)
... 
C
C++
Perl
Python
>>>

The break statement is used in the following for examples, and the break statement is used to jump out of the current loop body:

#!/usr/bin/python3
 
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    if site == "Runoob":
        print("教程!")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

After executing the script, it will jump out of the loop body when the loop reaches "Runoob":

循环数据 Baidu
循环数据 Google
教程!
完成循环!

range() function

If you need to traverse a sequence of numbers, you can use the built-in range() function. It will generate a sequence of numbers, for example:

>>>for i in range(5):
...     print(i)
...
0
1
2
3
4

You can also use range to specify the value of the interval:

>>>for i in range(5,9) :
    print(i)
 
    
5
6
7
8
>>>

You can also make the range start with a specified number and specify a different increment (even a negative number, sometimes this is also called a'step size'):

>>>for i in range(0, 10, 3) :
    print(i)
 
    
0
3
6
9
>>>

negative number:

>>>for i in range(-10, -100, -30) :
    print(i)
 
    
-10
-40
-70
>>>

You can combine the range() and len() functions to traverse the index of a sequence, as shown below:

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
>>>

You can also use the range() function to create a list:

>>>list(range(5))
[0, 1, 2, 3, 4]
>>>

break and continue statements and else in loops

break execution flow chart:
Insert picture description here
continue execution flow chart:
Insert picture description here

While statement code execution process:
Insert picture description here
for statement code execution process:
Insert picture description here
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 block will not be executed.
The continue statement is used to tell Python to skip the remaining statements in the current loop block, and then continue to the next loop.

Use break in while:

n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('循环结束。')

The output is:

4
3
循环结束。

Use continue in while:

n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束。')

The output is:

4
3
1
0
循环结束。

Examples are as follows:

#!/usr/bin/python3
 
for letter in 'Runoob':     # 第一个实例
   if letter == 'b':
      break
   print ('当前字母为 :', letter)
  
var = 10                    # 第二个实例
while var > 0:              
   print ('当期变量值为 :', var)
   var = var -1
   if var == 5:
      break
 
print ("Good bye!")

The output of executing the above script is:

当前字母为 : R
当前字母为 : u
当前字母为 : n
当前字母为 : o
当前字母为 : o
当期变量值为 : 10
当期变量值为 : 9
当期变量值为 : 8
当期变量值为 : 7
当期变量值为 : 6
Good bye!

The following example loops the string Runoob, and skips the output when it encounters the letter o:

#!/usr/bin/python3
 
for letter in 'Runoob':     # 第一个实例
   if letter == 'o':        # 字母为 o 时跳过输出
      continue
   print ('当前字母 :', letter)
 
var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:             # 变量为 5 时跳过输出
      continue
   print ('当前变量值 :', var)
print ("Good bye!")

The output of executing the above script is:

当前字母 : R
当前字母 : u
当前字母 : n
当前字母 : b
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Good bye!

The loop statement can have an else, which is executed when the list (with a for loop) or a condition becomes false (with a while loop) causing the loop to terminate, but it is not executed when the loop is terminated by a break.
The following example is used to query the loop example of prime numbers:

#!/usr/bin/python3
 
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '等于', x, '*', n//x)
            break
    else:
        # 循环中没有找到元素
        print(n, ' 是质数')

The output of executing the above script is:

2  是质数
3  是质数
4 等于 2 * 2
5  是质数
6 等于 2 * 3
7  是质数
8 等于 2 * 4
9 等于 3 * 3

pass statement

Python pass is an empty statement to maintain the integrity of the program structure.

pass does nothing, and is generally used as a placeholder statement, as in the following example:

>>>while True:
...     pass  # 等待键盘中断 (Ctrl+C)

The smallest class:

>>>class MyEmptyClass:
...     pass

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 ('执行 pass 块')
   print ('当前字母 :', letter)
 
print ("Good bye!")

The output of executing the above script is:

当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!

Guess you like

Origin blog.csdn.net/weixin_48372613/article/details/109748293