Python初级教程(10): if...else 语句

有时我们想在满足特定条件的情况下才执行代码,这时我们需要做决策。Python中的if…else语句就是用于做决策。

在本文中,您将学习使用不同形式的if...else语句来做决策。常见的形式有:

  • if语句

  • if...else语句

  • if...elif...else语句

  • 嵌套的if...else语句

下面结合例子来看下它们的详细用法:

1. if 语句

其语法为:

if test expression:
    statement(s)

流程图为:

图片.png

来看个例子:

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),只有它的值为Trueif中的语句才会执行。

当变量num的值为3时,num > 0的值为Trueif中的print(num, "is a positive number.")会执行。

当变量num的值为-1时,num > 0的值为Falseif中的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

流程图为:

图片.png
# 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 >= 0True,执行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
  • elifelse if的缩写。它允许我们测试多个表达式。

  • 如果if的测试表达式为False,它将检查下一个elif的测试表达式,依此类推。

  • 如果所有测试表达式都为False,则执行else主体。

  • 根据测试表达式,if...elif...else只会执行一个主体。

  • 只能有一个else块,但可以有多个elif块。

流程图为:

图片.png

看个例子:

# 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学堂”,我将定期更新相关文章。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容