People often say that life is a process of constantly making multiple choice questions: some people have no choice and only have one way to go; some people are better and can choose one of the two; some people with good ability or good family background can choose There are more choices; there are also some people who will wander around in circles and cannot find their direction during the confused period of life. For those who believe in God, it is as if God has planned a life route for us in advance, and it is also as if the gods have set many hardships in advance for Tang Zeng’s master and disciples to learn scriptures. God and gods control everything. Programming language can simulate all aspects of human life. Programmers, like gods and gods, can control the execution process of the program through special keywords in the programming language. These keywords constitute the process control statement.
Flow in programming languageControl statements are divided into the following categories:
Sequential statements
Branch statements
LoopStatements
Among them, sequential statements do not It requires a separate keyword to control, which means it is executed line by line, and no special instructions are required. The main things to talk about here are branch statements and loop statements.
1. Branch Statement
Conditional branch statement is a code block that determines which branch to execute based on the execution result (True/False) of one or more statements (judgment conditions). The branch statements provided in Python are: if..else statement, and no switch..case statement is provided. The if..else statement has the following forms:
Single branch:
if judgment condition:
Code block
If the code block of the single branch statement has only one statement, you can write the if statement and the code On the same line:
if Judgment condition: One sentence of code
Example: Determine whether the specified uid is the root user
uid = 0 if uid == 0: print("root")
You can also write like this:
uid = 0 if uid == 0: print("root")
Output result: root
Dual branch:
if Judgment condition:
Code block
else:
Code block
Example: Print user identity based on user id
uid = 100 if uid == 0: print("root") else: print("Common user")
Output result: Common user
Multiple branches:
if Judgment condition 1:
Code block 1
elif Judgment condition 2:
Code block 2
...
elif Judgment condition n:
Code block n
else:
Default code block
Example: Print letter grade based on student score
score = 88.8 level = int(score % 10) if level >= 10: print('Level A+') elif level == 9: print('Level A') elif level == 8: print('Level B') elif level == 7: print('Level C') elif level == 6: print('Level D') else: print('Level E')
Output result: Level B
Explanation:
When the expression in the above "judgment condition" can be any expression or any type of data Object instance. As long as the "true" value of the final return result of the judgment condition tests to True, it means that the condition is established and the corresponding code block will be executed; otherwise, it means that the condition is not established and the next condition needs to be judged.
2. Loop Statement
When we need to execute a code statement or code block multiple times, we can use a loop statement. The loop statements provided in Python are: while loop and for loop. It should be noted that there is no do..while loop in Python. In addition, there are several loop control statements used to control the loop execution process: break, continue and pass.
1. while loop
Basic form
The basic form of while loop statement is as follows:
while judgment condition:
Code block
When the given judgment condition When the truth test result of the return value is True, the code of the loop body is executed, otherwise the loop body is exited.
Example: Print numbers 0-9 in a loop
count = 0 while count <p style="text-align: left;"><br>Output result: 0 1 2 3 4 5 6 7 8 9<br>while infinite loop<br>When the judgment condition of while is always When True, the code in the while loop body will loop forever. <br>while True:<br> print("This is an infinite loop")<br>Output result: <br>This is an infinite loop<br>This is an infinite loop<br>This is an infinite loop<br>...<br>You can terminate the operation by Ctrl + C at this time. <br>while..else<br> Statement form: <br>while Judgment condition:<br> Code block<br>else:<br> Code block<br>The code block in else will be executed normally in the while loop If the while loop is interrupted by break, the code block in else will not be executed. <br>Example 1: The normal execution of the while loop ends (the statement in else will be executed)</p><pre class="brush:php;toolbar:false">count = 0 while count <p style="text-align: left;"><br>The execution result is: 0 1 2 3 4 5 6 7 8 9 end<br> Example 2: The while loop is interrupted (the statement in else will not be executed) </p><pre class="brush:php;toolbar:false">count = 0 while count <p style="text-align: left;"><br>输出结果:0 1 2 3 4 5<br><strong>2. for循环</strong><br>for循环通常用于遍历序列(如<a href="http://www.php.cn/wiki/1059.html" target="_blank">list</a>、tuple、<a href="http://www.php.cn/wiki/1078.html" target="_blank">range</a>、str)、集合(如 <a href="http://www.php.cn/code/8209.html" target="_blank">set</a>)和映射对象(如dict)。<br>基本形式<br>for循环的基本格式:<br>for 临时变量 in 可迭代对象:<br> 代码块<br>实例:遍历打印一个list中的元素</p><pre class="brush:php;toolbar:false">names = ['Tom', 'Peter', 'Jerry', 'Jack'] for name in names: print(name)
对于序列,也通过索引进行迭代:
names = ['Tom', 'Peter', 'Jerry', 'Jack'] for i in range(len(names)): print(names[i])
执行结果:
Tom
Peter
Jerry
Jack
for...else
与while..else基本一致,不再赘述。
3. 循环控制语句
循环控制语句可以更改循环体中程序的执行过程,如中断循环、跳过本次循环。
循环控制语句 说明
break 终止整个循环
contine 跳过本次循环,执行下一次循环
pass pass语句是个空语句,只是为了保持程序结构的完整性,没有什么特殊含义。pass语句并不是只能用于循环语句中,也可以用于分支语句中。
实例1:遍历0-9范围内的所有数字,并通过循环控制语句打印出其中的奇数
for i in range(10): if i % 2 == 0: continue print(i, end=' ')
输出结果:1 3 5 7 9
实例2:通过循环控制语句打印一个列表中的前3个元素
names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly'] for i in range(len(names)): if i >= 3: break print(names[i])
输出结果:
Tom
Peter
Jerry
4. 循环嵌套
循环嵌套是指:在一个循环体里面嵌入另一循环。
实例1:通过while循环打印99乘法表
j = 1 while j <p style="text-align: left;"><br>实例2:通过for循环打印99乘法表</p><pre class="brush:php;toolbar:false">for j in range(1, 10): for i in range(1, j+1): print('%d*%d=%d' % (i, j, i*j), end='\t') i += 1 print() j += 1
输出结果:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
The above is the detailed content of Python flow control statement methods. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools