Python3 – if、if..else、嵌套 if、if-elif 语句
现实生活中会出现一些情况,当我们需要做一些特定的任务时,根据一些特定的条件,我们决定下一步应该做什么。类似地,在编程中会出现一种情况,如果特定条件为真,则执行特定任务。在这种情况下,可以使用条件语句。以下是Python提供的条件语句。
- 如果
- 如果别的
- 嵌套 if
- if-elif 语句。
让我们通过所有这些。
if 语句
如果条件成立则执行块的简单代码,则使用 if 语句。这里提到的条件成立,那么块的代码运行,否则不运行。
句法:
if condition:
# Statements to execute if
# condition is true
流程图:-
例子:
Python3
# if statement example
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Python3
# if..else statement example
x = 3
if x == 4:
print("Yes")
else:
print("No")
Python3
# if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
Python3
# Nested if statement example
num = 10
if num > 5:
print("Bigger than 5")
if num <= 15:
print("Between 5 and 15")
Python3
# if-elif statement example
letter = "A"
if letter == B:
print("letter is B")
elif letter == "C":
print("letter is C")
elif num == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
输出:
10 greater than 5
Program ended
缩进(空白)用于分隔代码块。如上例所示,在 Python3 编码中必须使用缩进。
if..else 语句
在条件 if 语句中,附加代码块被合并为当 if 条件为假时执行的 else 语句。
语法:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
流程图:-
示例 1:
Python3
# if..else statement example
x = 3
if x == 4:
print("Yes")
else:
print("No")
输出:
No
示例 2:您还可以将 if..else 语句与多个条件链接。
Python3
# if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
输出:
letter is A
嵌套 if 语句
if 语句也可以在其他 if 语句中检查。此条件语句称为嵌套 if 语句。这意味着只有在外部 if 条件为真时才会检查内部 if 条件,由此,我们可以看到要满足的多个条件。
语法:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
流程图:-
例子:
Python3
# Nested if statement example
num = 10
if num > 5:
print("Bigger than 5")
if num <= 15:
print("Between 5 and 15")
输出:
Bigger than 5
Between 5 and 15
if-elif 语句
if-elif 语句是 if..else 链的快捷方式。在末尾使用 if-elif 语句时添加 else 块,如果上述 if-elif 语句都不为真,则执行该语句。
语法:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
流程图:-
例子:-
Python3
# if-elif statement example
letter = "A"
if letter == B:
print("letter is B")
elif letter == "C":
print("letter is C")
elif num == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
输出:
letter is A