Home Backend Development Python Tutorial Basics | Python flow control statements

Basics | Python flow control statements

Aug 15, 2023 pm 02:39 PM
python


This issue brings you the flow control statements that we often use when writing programs: Sequential execution statements, selection execution statements, and loop execution statements , the corresponding structures are: Sequential structure, selection structure (branch structure), loop structure,Hope to help you Helps.

Basics | Python flow control statements


#

1. Sequential structure

The sequential structure has no keywords. The default execution structure of the computer program is the sequential structure, that is, from top to bottom, from left to right, sequential execution.


##2. Select structure

2.1 Single branch

Statement format:

if 判断条件:
    代码块
Copy after login
If the code block of a single branch statement has only one statement, you can write the if statement and the code on the same line:
if 判断条件: 一句代码
Copy after login

Example:

"""
登录密码
"""

user = 'Python 当打之年'
password = '123456'

# 用法1
if user == 'Python 当打之年':
    print('用户名正确!')

# 用法2
if password == '123456': print('密码正确!')

# 用法3
if user == 'Python 当打之年':
    if password == '123456':
        print('用户名和密码正确!')

# 用法4
if user == 'Python 当打之年' and password == '123456':
    print('用户名和密码正确!')
Copy after login


##2.2 Dual Branch

语句格式

if 判断条件:
    代码块1
else:
    代码块2
Copy after login
如果判断条件为真,则执行代码块1,否则执行代码块2
示例:
user = 'Python 当打之年'
password = '123456'

if user == 'Python 当打之年':
    print('用户名正确!')
else:
    print('用户名错误!')
if password == '123456':
    print('密码正确!')
else:
    print('密码错误!')
Copy after login


2.3 多分支

语句格式

if 判断条件1:
    代码块1
elif 判断条件2:
    代码块2
...
elif 判断条件n:
    代码块n
else:
    代码块n+1
Copy after login

依次遍历每个判断条件,如果判断条件为真,则执行相应代码块,否则执行最后一个代码块,所有代码块中有且仅有一个代码块会被执行。

示例:
"""
成绩等级
"""
score = float(input('请输入成绩: '))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'
print('学生成绩等级为: ', grade)
Copy after login



3. 循环结构

3.1 for循环

语句格式

for 迭代变量 in 可迭代对象:
    循环体语句
Copy after login

依次遍历迭代对象,执行循环体语句

示例:
for i in range(10):
    print('i = ', i)

# 100以内偶数和
sum = 0
for i in range(2, 101, 2):
    sum += i
print('sum = ', sum)
Copy after login

关于 range (前闭后开):

range(100): Generate an integer ranging from 0 to 100. Note that 100 cannot be obtained.

range(1, 100): Generate an integer ranging from 1 to 100.

range(1, 100, 2): Generate odd numbers from 1 to 100, 2 is the step size.

range(100, 0, -2): Generate an even number from 100 to 1, -2 is the step size.

3.2 while循环

语句格式

while 判断条件:
    代码块
Copy after login

当判断条件为真时,执行代码块,直到判断条件为假时退出。

示例:
# 用法1
i = 0
while i < 10:
    print(&#39;i = &#39;, i)
    i += 1

# 用法2
i = 0
while True:
    if i < 10:
        print(&#39;i = &#39;, i)
        i += 1
    else:
        break
Copy after login
注意:代码块内一定要有退出条件,否则会出现死循环

3.3 break、continue、pass

break: 在代码块执行过程中终止循环,并且跳出整个循环

continue: Terminate the current loop during the execution of the code block, jump out of the loop, and execute the next loop.

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

Example:

"""
输出 0-10 之间大于 2 的奇数
"""
n = 10
while n > 0:
    n -= 1
    if n == 2:
        break
    if n % 2 == 0:
        continue
    else:
        pass
        print(&#39;执行pass语句&#39;)
        print(n)
        
# 执行pass语句
# 9
# 执行pass语句
# 7
# 执行pass语句
# 5
# 执行pass语句
# 3
Copy after login
3.4 嵌套循环结构

语句格式

# while 嵌套
while 条件表达式1:
   while 条件表达式2:
   循环体2
   循环体1

# for 嵌套
for 迭代变量1 in 迭代对象1:
   for 迭代变量2 in 迭代对象2:
   循环体2
   循环体1
Copy after login
也可以在循环体内嵌入其他的循环体,如在while循环中嵌入for循环, 在for循环中嵌入while循环。

示例:

"""
九九乘法表
"""
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f&#39;{i}*{j}={i * j}&#39;, end=&#39;\t&#39;)
    print()
    
# 1*1=1
# 2*1=2 2*2=4
# 3*1=3 3*2=6 3*3=9
# 4*1=4 4*2=8 4*3=12 4*4=16
# 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
# 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
# 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
# 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
# 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
Copy after login

The above is the detailed content of Basics | Python flow control statements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

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.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

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.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

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.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles