Learn to use if, else and elif to implement conditional judgment

When writing a program, it is often necessary to execute different blocks of code according to different conditions. ifThe elseand statements in Python elifare used to implement conditional judgments. The following are examples of how to use these statements:

# 示例 1: 基本的 if-else 条件判断
x = 10

if x > 5:
    print("x 大于 5")
else:
    print("x 不大于 5")

# 示例 2: 使用 elif 处理多个条件
y = 7

if y > 10:
    print("y 大于 10")
elif y > 5:
    print("y 大于 5,但不大于 10")
else:
    print("y 不大于 5")

# 示例 3: 多个条件判断嵌套
z = 3

if z > 0:
    if z > 2:
        print("z 大于 2")
    else:
        print("z 不大于 2,但是大于 0")
else:
    print("z 不大于 0")

# 示例 4: 使用逻辑运算符结合多个条件
a = 15

if a > 10 and a < 20:
    print("a 大于 10 且小于 20")

# 示例 5: 使用 not 关键字取反条件
b = 25

if not b < 20:
    print("b 不小于 20")

In these examples, ifstatements are used to check whether a condition is true, and if the condition is true, the corresponding block of code is executed. elseCan be used to execute an alternative block of code if the condition is false . Whereas elifstatements can be used to select between multiple conditions. You can also combine multiple conditions using logical operators such as and, or, not.

Remember, indentation in Python is very important, it represents the hierarchy of code blocks. The code block following the conditional statement needs to be indented appropriately.

Guess you like

Origin blog.csdn.net/m0_72605743/article/details/132412240