if 语句
- 简单示例
cars=["audi","bmw","subaru","toyota"]
for car in cars:
if car=="bmw":
print(car.upper())
else:
print(car.title())
- 不相等 !=
requested_topping="mushrooms"
if requested_topping != "anchovies":
print("Hold the anchovies")
- 使用关键字 and 检查多个条件,同时满足
- 使用关键字 or 检查多个条件,至少一个满足
#使用关键字and检查多个条件,同时满足
age_0=21
age_1=22
print((age_0>20) and (age_1>20))
#使用关键字 or 检查多个条件,至少一个满足
age_0=21
age_1=18
print((age_0>20) or (age_1>20))
- 检查特定值是否包含在列表中,in
- 检查特定值是否不包含在列表中,not in
requested_toppings=["mushrooms","onions","pineapple"]
print("mushrooms" in requested_toppings)
requested_toppings=["mushrooms","onions","pineapple"]
print("onions" not in requested_toppings)
-
布尔表达式
结果要么True 要么 Fasle -
if-else 语句
age = 17
if age >=18 :
print("You are old enough to vote !")
print("Have you registered to vote yet?")
else:
print("Sorry , you are too young to vote!")
- if-elif-else 语句
#if-elif-else 语句
age=12
if age<4:
price=0
elif age<18:
price=5
else:
price=10
print("Your admission cost is $"+str(price)+" !")
#使用多个 elif 代码块
age=12
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
else:
price=5
print("Your admission cost is $"+str(price)+" !")
#省略 else 代码块
age =12
if age < 4:
price=0
elif age <18:
price=5
elif age <65:
price=10
elif age >=65:
price=5
print("Your admission caot is $"+str(price)+" !")
- 使用 if 语句处理列表
requested_toppings=["mushrooms","greenpeppers","extra cheese"]
for requested_topping in requested_toppings:
if requested_topping == "greenpeppers":
print("Sorry , we are out of "+requested_topping+" !")
else:
print("Adding "+requested_topping+" !")
print("\nFinished making your pizza")