Python by Example 中文版:选择结构

我们每天都面临着选择,程序设计时也有这样的事,Python提供了选择结构来处理这样的事情。 选择结构由3部分组成:关键字(if, elif, else), 判断结果真假的条件表达式,代码块。 上下相邻且具有相同缩进长度的语句是一个代码块。

判断一个数为正数,负数或零

x = 9

if是关键字, “x<0”是判断真假的条件表达式, print(“x = “, x)与print(“It is the negative number.”)组成代码块

if x < 0:
    print("x = ", x)
    print("It is the negative number.")

elif是关键字, “x>0”是判断真假的条件表达式, print(“x = “, x)与print(“It is the positive number.”)组成代码块

elif x > 0:
    print("x = ", x)
    print("It is the positive number.")

else是关键字, else后面没有条件表达式, print(“x = “, x)与print(“It is zero”)组成代码块

else:
    print("x = ", x)
    print("It is zero.")

判断一个数是奇数或偶数

x = 7
print("x = ", x)

if是关键字, “x%2 == 1”是判断结果真假的条件表达式,

if x%2 == 1:
    print("It is the odd number")
else:
    print("It is the odd number")

判断一个数是否为3位数, 如是,打印出来 “x >= 100 and x <= 999”是判断结果真假的条件表达式,

x = 345
if x >= 100 and x <= 999:
    print("x = ", x)

运行if-1.py

$ python if-1.py
x =  9
It is the positive number.
x =  7
It is the odd number
x =  345

下一个例子: 三元操作符.