05-Python-判断语句
1、条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。条件测试为True,则执行;否则,不执行。
1.1、检查特定值是否包含在列表中
1 banned_users = ['andrew','carolina','david'] 2 user = 'marie' 3 4 if user in banned_users: 5 print(user.title() + ", you can post a response if you wish.") 6 if user not in banned_users: 7 print(user.title() + " doesn't exist in list.")
1.2、布尔表达式
布尔表达式结果要么为True,要么为False。空字符串、列表、元组、字典等都为假。
1 bool([]) #值为False 2 bool({}) #值为False 3 bool([]) #值为False 4 bool("") #值为False 5 bool(0) #值为False 6 7 bool(1) #值为True 8 bool(-1) #值为True
1.3、if-elif-else
1 if <条件判断1>: 2 <执行1> 3 elif <条件判断2>: 4 <执行2> 5 elif <条件判断3>: 6 <执行3> 7 else: 8 <执行4> 9 10 #举例 11 age = int(input("please input your age: ")) 12 13 if age < 4: #4岁以下免费 14 price = 0 15 elif age < 18: #4~17岁5块 16 price = 5 17 elif age < 65: #18~64岁10块 18 price = 10 19 else: #大于等于65岁的半价 20 price = 5 21 22 print("Your admission cost is $" + str(price) + ".")
1.4、测试多个条件
if-elif-else功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后后,Python会跳过余下的测试。如果有时候需要关心所有的检测条件,则不能使用if-elif-else这种结构,而应该使用多个if语句。
1 #如果顾客点了两种配料,就需要确保在其披萨中包含'mushrooms'和'extra cheese'。 2 requested_toppings = ['mushrooms','extra cheese'] 3 4 if 'mushrooms' in requested_toppings: 5 print("Adding mushrooms.") 6 if 'pepperoni' in requested_toppings: 7 print("Adding pepperoni.") 8 if 'extra cheese' in requested_toppings: 9 print("Adding extra cheese:") 10 11 print("\nFinished making your pizza!")
2、用if语句处理列表
2.1、处理特殊元素
1 requested_toppings = ['mushrooms','green peppers','extra cheese'] 2 3 for requested_topping in requested_toppings: 4 if requested_topping == 'green peppers': #如果点了青椒,则打印青椒没了。 5 print("Sorry,we are out of green peppers right now.") 6 else: 7 print("Adding " + requested_topping + ".") 8 9 print("\nFinished making your pizza!")
2.2、确定列表不是空的
1 requested_toppings = [] 2 3 if requested_toppings: #为真就执行循环体 4 for requested_topping in requeted_toppings: 5 print("Adding " + requested_topping + ".") 6 print("\nFinished making your pizza!") 7 else: 8 print("You get a plain pizza!")
2.3、使用多个列表
1 available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] 2 requested_toppings = ['mushrooms','french fries','extra cheese'] 3 4 for requested_topping in requested_toppings: 5 if requested_topping in available_toppings: 6 print("Adding " + requested_topping + ".') 7 else: 8 print("Sorry, we don't have " + requested_topping + ".") 9 10 print("\nFinished making your pizza!")