Home Backend Development Python Tutorial What are the common flow control structures in Python?

What are the common flow control structures in Python?

Jan 20, 2024 am 08:17 AM
for if-else while

What are the common flow control structures in Python?

What are the common flow control structures in Python?

In Python, the flow control structure is an important tool used to determine the execution order of the program. They allow us to execute different blocks of code based on different conditions, or to execute a block of code repeatedly. The following will introduce common process control structures in Python and provide corresponding code examples.

  1. Conditional statements (if-else):
    Conditional statements allow us to execute different code blocks based on different conditions. Its basic syntax is:

    if 条件1:
     # 当条件1成立时执行的代码块
    elif 条件2:
     # 当条件2成立时执行的代码块
    else:
     # 当以上条件都不成立时执行的代码块
    Copy after login

    Sample code:

    age = 18
    if age >= 18:
     print("你已经成年了")
    else:
     print("你还未成年")
    Copy after login

    Output result:

    你已经成年了
    Copy after login
  2. Loop statement:
    Loop statement allows us to repeatedly execute a piece of code multiple times until a certain condition is met. There are two common loop statements in Python: for loop and while loop.

2.1 for loop:
The for loop is used to traverse each element in an iterable object (such as a list, string, etc.) and execute the corresponding code block. Its basic syntax is:

for 变量 in 可迭代对象:
    # 执行的代码块
Copy after login

Sample code:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)
Copy after login

Output result:

apple
banana
orange
Copy after login

2.2 while loop:
The while loop is used to repeatedly execute a piece of code. until the condition no longer holds true. Its basic syntax is:

while 条件:
    # 执行的代码块
    # 更新条件,避免无限循环
Copy after login

Sample code:

count = 0
while count < 5:
    print("Count:", count)
    count += 1
Copy after login

Output result:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Copy after login
  1. Jump statement:
    Jump statement is used in the code Skip certain codes or break out of loops during execution. Common jump statements in Python include break, continue and return.

3.1 break statement:
The break statement is used to terminate the loop and jump out of the loop body. It can be used anywhere within a loop to terminate the loop early. Sample code:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)
Copy after login

Output result:

apple
Copy after login

3.2 continue statement:
The continue statement is used to terminate the current iteration and jump to the next iteration. It can be used anywhere within a loop to skip certain code. Sample code:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    if fruit == "banana":
        continue
    print(fruit)
Copy after login

Output result:

apple
orange
Copy after login

3.3 return statement:
The return statement is used in functions to return the execution result of the function and end the execution of the function. It can also be used to break out of loops. Sample code:

def sum_numbers(numbers):
    total = 0
    for number in numbers:
        if number == 0:
            return total
        total += number

numbers = [1, 2, 3, 0, 4, 5]
result = sum_numbers(numbers)
print("Sum:", result)
Copy after login

Output result:

Sum: 6
Copy after login

The above are the common process control structures in Python. Through conditional statements, loop statements and jump statements, we can flexibly control the execution flow of the program. , making it more in line with our needs.

The above is the detailed content of What are the common flow control structures in Python?. 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)

17 ways to solve the kernel_security_check_failure blue screen 17 ways to solve the kernel_security_check_failure blue screen Feb 12, 2024 pm 08:51 PM

Kernelsecuritycheckfailure (kernel check failure) is a relatively common type of stop code. However, no matter what the reason is, the blue screen error causes many users to be very distressed. Let this site carefully introduce 17 types to users. Solution. 17 solutions to kernel_security_check_failure blue screen Method 1: Remove all external devices When any external device you are using is incompatible with your version of Windows, the Kernelsecuritycheckfailure blue screen error may occur. To do this, you need to unplug all external devices before trying to restart your computer.

In C language, what is the difference between while(1) and while(0)? In C language, what is the difference between while(1) and while(0)? Aug 31, 2023 am 10:45 AM

We know that in C language, 'while' keyword is used to define a loop that works based on the condition passed to the loop. Now, since the condition can have two values, true or false, the code inside the while block will be executed repeatedly if the condition is true and will not be executed if the condition is false. Now, by passing parameters to the while loop, we can differentiate between while(1) and while(0) because while(1) is a loop where the condition is always considered true and hence the code inside the block will start executing repeatedly. Furthermore, we can state that it is not 1 that is passed to the loop that makes the condition true, but if any non-zero integer is passed to the while loop, then it will be considered as the true condition, so

How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer How to uninstall Skype for Business on Win10? How to completely uninstall Skype on your computer Feb 13, 2024 pm 12:30 PM

Can Win10 skype be uninstalled? This is a question that many users want to know, because many users find that this application is included in the default program on their computers, and they are worried that deleting it will affect the operation of the system. Let this website help users Let’s take a closer look at how to uninstall Skype for Business in Win10. How to uninstall Skype for Business in Win10 1. Click the Windows icon on the computer desktop, and then click the settings icon to enter. 2. Click "Apply". 3. Enter "Skype" in the search box and click to select the found result. 4. Click "Uninstall". 5

How did our company completely eliminate 2,000 if-else in the project? How did our company completely eliminate 2,000 if-else in the project? Jul 26, 2023 pm 04:29 PM

First, get all the types in the assembly that implement the common interface IOrderOutputStrategy. Then, we create a dictionary, the name of the displayName of the formatter is key, and the type is value. Then select the formatter type from the dictionary and try to instantiate the policy object.

How to use for to find the factorial of n in JavaScript How to use for to find the factorial of n in JavaScript Dec 08, 2021 pm 06:04 PM

How to use for to find n factorial: 1. Use the "for (var i=1;i<=n;i++){}" statement to control the loop traversal range to "1~n"; 2. In the loop body, use "cj *=i" Multiply the numbers from 1 to n, and assign the product to the variable cj; 3. After the loop ends, the value of the variable cj is the factorial of n, and then output it.

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

How to write if-else elegantly in Java How to write if-else elegantly in Java Apr 29, 2023 pm 10:04 PM

1. The switch method has good effects on enumeration value processing. For example, different processing needs to be done for different order statuses. Because the status values ​​are limited, then we can directly use switch to do different processing for different statuses: Original Statement publicvoidbefore(Integerstatus){if(status==1){System.out.println("Order not received");}elseif(status==2){System.out.println("Order not shipped") ;}elseif(status==3

Is while a keyword in go language? Is while a keyword in go language? Jun 04, 2021 pm 05:01 PM

In the Go language, while is not a keyword. You can use the for statement plus break to achieve the effect of a while loop, such as "for {sum++ if sum>10{break}else{...}}". The go language has 25 keywords such as break, default, func, select, case, defer, go, map, else, goto, for, if, var, etc.

See all articles