条件语句#

在本课程及第6与第7课程中,我们将了解 Python 中条件语句的结构,以及如何使用它们在Python中编写 DRY((Don’t Repeat Yourself)代码。

通过实现编写代码的 DRY 策略,我们可以使代码:

  1. 更容易理解和阅读,从而支持可重复性。

  2. 更容易更新,因为只需更新一次指定任务的代码,而不是重复代码块的每个实例。

虽然有许多提高效率和消除代码重复的策略,但三种常用的 DRY 策略是条件语句循环函数。本课程介绍Python中的条件语句,它可以通过仅在满足某些条件时执行代码来控制代码的流动。

1. 条件语句的结构#

条件语句使用基于ifelse语句(每个以冒号结尾:)的语法结构,这些语句定义了可以根据条件是否为真来完成的潜在操作。如果语句满足提供的条件if(即结果为True),则将执行特定代码。如果不满足该条件(即结果为False),则将执行else语句提供的代码,例如:

if condition:
    print("Condition is true, and this statement is printed.")    
else:
    print("Condition is false (i.e. not true), so a different statement is printed.")

注: ifelse下的代码是必须有缩进的,输入:回车会自动缩进

2. 使用条件语句比较数值#

我们可以编写使用比较运算符(例如等于==<>)的条件语句来检查变量的值与其他值或变量。

例如,可以检查变量的值是否等于 (==) 某个值。

#Set x to 10
x = 10
#Compare x to 10
if x == 10:
    print("x is equal to 10.")       
else:
    print("x has a value of", x, "which is not equal to 10.")   
x is equal to 10.
#Set x to 0
x = 0
#Compare x to 10
if x == 10:
    print("x is equal to 10.")     
else:
    print("x has a value of", x, "which is not equal to 10.")    
x has a value of 0 which is not equal to 10.

3. 使用条件语句检查值#

可以使用成员运算符(例如innot in)编写条件语句来检查某些值是否包含在数据结构中,例如列表,甚至是文本字符串。

#Create list of average monthly precip (inches) in Boulder, CO
avg_monthly_precip = [0.70,  0.75, 1.85, 2.93, 3.05, 2.02, 
                      1.93, 1.62, 1.84, 1.31, 1.39, 0.84]
#Check for value 0.70 in list
if 0.70 in avg_monthly_precip:
    print("Value is in list.")    
else:     
    print("Value is not in list.")
Value is in list.
#Check for value 0.71 in list
if 0.71 in avg_monthly_precip:
    print("Value is in list.")    
else:     
    print("Value is not in list.")
Value is not in list.

使用not in以检查该值是否不在列表中:

#Check that value 0.71 not in list
if 0.71 not in avg_monthly_precip:
    print("Value is not in list.")    
else:     
    print("Value is in list.")
Value is not in list.

还可以使用成员运算符来检查文本字符串中的特定单词:

#Check for string "precip" within text string "avg_monthly_temp"
if "precip" in "avg_monthly_temp":
    print("This textstring contains the word precip.")    
else:
    print("This textstring does not contain the word precip.")
This textstring does not contain the word precip.

4. 使用条件语句检查对象类型#

还可以使用标识运算符(例如isis not)编写条件语句来检查对象是否属于某种类型(例如intstrlist

#Set x to 0
x = 0
#Check if x is type integer
if type(x) is int:
    print(x, "is an integer.")   
else:
    print(x, "is not an integer.")
0 is an integer.
#Check if x is not type string
if type(x) is not str:
    print(x, "is not a string.")    
else:
    print(x, "is a string.")
0 is not a string.
#Create list of abbreviated month names
months = ["Jan", "Feb", "Mar", "Apr", "May", "June",
         "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
if type(months) is list:
    print("Object is a list.")    
else:
    print("Object is not a list.")
Object is a list.

5. 具有替代条件的条件语句#

我们可以扩展if语法,使用替代条件elif 。不满足if语句提供的第一个条件(即结果为False),Python则将检查elif语句提供的条件。如果elif满足条件,那么提供的代码将执行。如果既不满足if也不满足elif条件,则将执行else提供的代码。

if condition:
    print("First condition is true.")    
elif alternative_condition:
    print("First condition is not true but alternative condition is true.")    
else:
    print("Neither of these conditions is true, so this statement is printed.")

示例:

#Set x equal to 5 and y equal to 10
x = 5
y = 10
#Execute code based on comparison of x to y
if x < y:
    print("x started with value of", x)    
    x += 5    
    print("It now has a value of", x, "which is equal to y.")
elif x > y:
    print("x started with value of", x)    
    x -= 5    
    print("It now has a value of", x, "which is equal to y.")
else:
    print("x started with a value of", x, "which is already equal to y.")
x started with value of 5
It now has a value of 10 which is equal to y.

同时我们还可以将elif语法应用于使用其他运算符或检查文本字符串或对象的值的结构条件语句。

6. 条件组合的条件语句#

逻辑运算符(例如and, or, not)允许我们创建可以检查条件组合的条件语句:

  • and如果满足所有指定条件,则执行代码

  • or如果至少满足一个指定条件,则执行代码

  • not仅在指定条件不满足时才执行代码(not可以和and或者or结合使用来检查是否不满足多个条件)

6.1 使用and检查两个条件#

#Set x equal to 5 and y equal to 10
x = 5
y = 10
#Add x and y if they are both integers
if type(x) is int and type(y) is int:
    print(x + y)    
else:
    print("Either x or y is not an integer.")
15

6.2 使用or检查至少一个条件#

#Set x equal to 0 and y equal to 10
x = 0
y = 10
#Check whether either is equal to zero
if x == 0 or y == 0:
    print("Either x or y is equal to 0.")    
    x += 1    
    y += 1    
    print("x is now", x, "and y is now", y)
else:
    print("Neither x nor y is equal to 0.")
Either x or y is equal to 0.
x is now 1 and y is now 11