Python3简明教程(四)—— 流程控制之分支

我们通过 if-else 语句来做决定,来改变程序运行的流程。

if语句

语法如下:

if expression:
    do this

如果表达式 expression 的值为真(不为零的任何值都为真),程序将执行缩进后的内容。务必要使用正确的缩进,在表达式为真的情况将会执行缩进的所有行。

例如,检查一个数是否小于100:

#!/usr/bin/env python3
number = int(input("Enter a number: "))
if number < 100:
    print("The number is less than 100")

真值检测

检测真值的优雅方式是这样的:

if x:
    pass

不要像下面这样做:

if x == True:
    pass

else语句

我们使用 else 语句在 if 语句未满足的情况时工作。

例如,对上面程序的补充:

#!/usr/bin/env python3
number = int(input("Enter a number: "))
if number < 100:
    print("The number is less than 100")
else:
    print("The number is greater than 100")

还有多个分支的情况

>>> x = int(input("Please enter an integer: "))
>>> if x < 0:
...      x = 0
...      print('Negative changed to zero')
... elif x == 0:
...      print('Zero')
... elif x == 1:
...      print('Single')
... else:
...      print('More')

请注意,elif 虽然是else if 的简写,但编写程序时并不能把它们展开写。

参考链接:https://www.shiyanlou.com/courses/596

原文地址:https://www.cnblogs.com/lfri/p/10369158.html