Python flow control statement methods
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 <= 9: print(count, end=' ') count += 1
Output result: 0 1 2 3 4 5 6 7 8 9
while infinite loop
When the judgment condition of while is always When True, the code in the while loop body will loop forever.
while True:
print("This is an infinite loop")
Output result:
This is an infinite loop
This is an infinite loop
This is an infinite loop
...
You can terminate the operation by Ctrl + C at this time.
while..else
Statement form:
while Judgment condition:
Code block
else:
Code block
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.
Example 1: The normal execution of the while loop ends (the statement in else will be executed)
count = 0 while count <=9: print(count, end=' ') count += 1 else: print('end')
The execution result is: 0 1 2 3 4 5 6 7 8 9 end
Example 2: The while loop is interrupted (the statement in else will not be executed)
count = 0 while count <=9: print(count, end=' ') if count == 5: break count += 1 else: print('end')
输出结果:0 1 2 3 4 5
2. for循环
for循环通常用于遍历序列(如list、tuple、range、str)、集合(如 set)和映射对象(如dict)。
基本形式
for循环的基本格式:
for 临时变量 in 可迭代对象:
代码块
实例:遍历打印一个list中的元素
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 <= 9: i = 1 while i <= j: print('%d*%d=%d' % (i, j, i*j), end='\t') i += 1 print() j += 1
实例2:通过for循环打印99乘法表
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
