有时我们想在满足特定条件的情况下才执行代码,这时我们需要做决策。Python中的if…else
语句就是用于做决策。
在本文中,您将学习使用不同形式的if...else
语句来做决策。常见的形式有:
if
语句if...else
语句if...elif...else
语句嵌套的
if...else
语句
下面结合例子来看下它们的详细用法:
1. if 语句
其语法为:
if test expression:
statement(s)
流程图为:
来看个例子:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
输出为:
3 is a positive number.
This is always printed.
This is also always printed.
在上面的例子中,num > 0
是个测试表达式(test expression),只有它的值为True
时if
中的语句才会执行。
当变量num
的值为3
时,num > 0
的值为True
,if
中的print(num, "is a positive number.")
会执行。
当变量num
的值为-1
时,num > 0
的值为False
,if
中的print(num, "is a positive number.")
将不会执行,直接跳过。
由于print("This is always printed.")
和print("This is also always printed.")
语句(未缩进)位于if
代码块之外,因此无论测试表达式如何,它们都将执行。
2. if...else 语句
其语法为:
if test expression:
Body of if
else:
Body of else
流程图为:
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print(num, "is a positive number or zero")
else:
print(num, "is a negative number")
输出为:
3 is a positive number or zero
在上面的例子中,当num = 3
时,测试表达式num >= 0
为True
,执行if
主体,跳过else
主体。
如果num = -5
,测试表达式为False
,执行else
的主体,跳过if
的主体。
如果num = 0
,测试表达式为True
,执行if
的主体,跳过else
的主体。
3. if...elif...else 语句
其语法为:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
elif
是else if
的缩写。它允许我们测试多个表达式。如果
if
的测试表达式为False
,它将检查下一个elif
的测试表达式,依此类推。如果所有测试表达式都为
False
,则执行else
主体。根据测试表达式,
if...elif...else
只会执行一个主体。只能有一个
else
块,但可以有多个elif
块。
流程图为:
看个例子:
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
输出为:
Positive number
当变量num
为正数时,打印"Positive number"。
如果num
等于0,则打印"Zero"。
如果num
为负数,则打印"Negative number"。
4. 嵌套的 if...else语句
我们可以在if ... elif ... else
语句中包含另一个if ... elif ... else
语句,称为嵌套。缩进是弄清楚嵌套级别的唯一方法。
来看个例子:
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
输出为:
Enter a number: 4
Positive number
或输出为:
Enter a number: -2
Negative number
或输出为:
Enter a number: 0
Zero
今天的内容就讲到这。
感谢您的阅读!想了解更多有关R语言技巧,请关注我的微信公众号“R语言和Python学堂”,我将定期更新相关文章。