Home > Backend Development > Python Tutorial > What is the basic format of if statement in Python

What is the basic format of if statement in Python

王林
Release: 2023-05-11 17:49:12
forward
4013 people have browsed it

In Python, if statements are used to execute different blocks of code based on conditions. Its basic format is as follows:

if condition:
    # 如果 condition 为 True,执行这里的代码块
Copy after login

Among them, condition is an expression, usually involving variables and operators, used to determine whether the result is True or False.

If condition is True, the indented code block is executed.

If condition is False, skip the code block and continue executing the next line of code.

If you need to test multiple conditions, you can use the if...elif...else structure. elif is the abbreviation of else if, which means testing the next condition if the previous condition is not met. else is used to handle all other cases, i.e. if none of the previous conditions are met, the else block of code is executed. Its basic format is as follows:

if condition1:
    # 如果 condition1 为 True,执行这里的代码块
elif condition2:
    # 否则如果 condition2 为 True,执行这里的代码块
else:
    # 否则执行这里的代码块
Copy after login

Here are some examples:

# 如果 a 大于 b,则输出 "a 大于 b";否则输出 "a 小于等于 b"
a = 10
b = 5
if a > b:
    print("a 大于 b")
else:
    print("a 小于等于 b")

 # 如果 x 是正数,则输出 "x 是正数";否则如果 x 是负数,则输出 "x 是负数";否则输出 "x 是零"
x = -3
if x > 0:
    print("x 是正数")
elif x < 0:
    print("x 是负数")
else:
    print("x 是零")
Copy after login

In Python, nested if statements are used to nest another if statement within a block of code within an if statement. This allows you to test more complex conditions. The basic format of a nested if statement is as follows:

if condition1:
    # 如果 condition1 为 True,执行这里的代码块
    if condition2:
        # 如果 condition2 为 True,执行这里的代码块
    else:
        # 如果 condition2 为 False,执行这里的代码块
else:
    # 如果 condition1 为 False,跳过代码块并继续执行下一行代码
Copy after login

Here are some examples:

# 如果 a 大于 b,则进一步检查 a 是否大于 c
a = 10
b = 5
c = 7
if a > b:
    print("a 大于 b")
    if a > c:
        print("a 大于 c")
    else:
        print("a 小于等于 c")
else:
    print("a 小于等于 b")
 
# 检查两个数是否均为偶数
num1 = 4
num2 = 8
if num1 % 2 == 0:
    if num2 % 2 == 0:
        print("两个数均为偶数")
    else:
        print("只有一个数是偶数")
else:
    print("两个数均为奇数")
Copy after login

The above is the detailed content of What is the basic format of if statement in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template