Home  >  Article  >  Backend Development  >  Master these flow control statements to ensure that your Python program executes smoothly!

Master these flow control statements to ensure that your Python program executes smoothly!

WBOY
WBOYOriginal
2024-01-20 08:41:20835browse

Master these flow control statements to ensure that your Python program executes smoothly!

Want to write Python programs smoothly? Master these flow control statements first!

Python is a simple and elegant programming language that is widely used in various fields, from web development to data science. In the process of writing Python programs, flow control statements play a vital role in helping the program execute according to our expectations.

This article will introduce you to the most commonly used flow control statements in Python, and provide specific code examples to help readers better understand and use these statements.

1. Conditional statement (if-else statement)

Conditional statement executes different code blocks based on the true or false condition. The following is the basic syntax structure of the conditional statement:

if condition:
    # 如果条件为真,则执行此代码块
else:
    # 如果条件为假,则执行此代码块

Example 1: Determine the grade based on the grades entered by the user

score = float(input("请输入你的成绩: "))

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("E")

In the above example, the corresponding grades are printed out based on different grade ranges.

2. Loop statements (for loops and while loops)

Loop statements can repeatedly execute a piece of code, and can be used to traverse a sequence, perform a fixed number of operations, etc. Python provides two commonly used loop statements: for loop and while loop.

  1. for loop

The for loop is used to traverse an iterable object (such as a list, string, etc.), take out the elements one by one, and execute a piece of code. The following is the basic syntax structure of a for loop:

for item in iterable:
    # 对item执行某些操作

Example 2: Calculate the sum of integers between 1 and 10

sum = 0

for i in range(1, 11):
    sum += i

print("1到10之间的整数之和为:", sum)

In the above example, a for loop is used to traverse range(1, 11 ), add each element of the integer sequence to the sum variable, and finally output the result.

  1. while loop

The while loop is used to repeatedly execute a piece of code when a condition is met. The following is the basic syntax structure of the while loop:

while condition:
    # 在条件满足时执行此代码块

Example 3: Using the while loop to calculate the Fibonacci sequence

a, b = 0, 1

while b < 1000:
    print(b, end=' ')
    a, b = b, a + b

In the above example, the while loop is used to generate the Fibonacci sequence, Until the elements in the array are greater than 1000.

3. Break out of the loop (break and continue statements)

Sometimes, we want to jump out of a specific condition in the loop or skip a certain loop directly. Python provides two keywords to achieve this function: break and continue.

  1. break statement: When a certain condition is met, terminate the current loop.

Example 4: Find an element in the list

fruits = ['apple', 'banana', 'orange', 'grape', 'mango']

for fruit in fruits:
    if fruit == 'orange':
        print("找到了橙子!")
        break
else:
    print("没有找到橙子!")

In the above example, if the orange is found during the loop using the break statement, the loop will be terminated and the corresponding output will be result.

  1. continue statement: When a certain condition is met, skip the remaining code of the current loop and directly enter the next loop.

Example 5: Print odd numbers between 1 and 10

for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i, end=' ')

In the above example, use the continue statement to exclude even numbers and only print out odd numbers between 1 and 10.

Summary:

Mastering flow control statements is the basis for writing Python programs. When writing programs, we often need to perform different operations based on different conditions, or repeatedly execute a piece of code multiple times. Through conditional statements and loop statements, we can achieve these requirements well, and use break and continue statements to control the loop process more flexibly.

I hope that through the introduction and sample code of this article, readers can better understand and master the usage of flow control statements in Python, and use them flexibly in the actual process of writing programs to write efficient and elegant Python programs. .

The above is the detailed content of Master these flow control statements to ensure that your Python program executes smoothly!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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