一、简单示例
#简单示例1
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
#注:两个等号是发问(必须是俩等号)
print(car.upper())
else:
print(car.title())
#输出Audi
#BMW
#Subaru
#Toyota
二、if 语句
1. if 语句
代码如下(示例):
age = 19
if age >= 18:
print("You are old enough to vote!")
#输出You are old enough to vote!
2. if-else语句
age = 19
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry,you are too young to vote.")
#输出You are old enough to vote!
3. if-elif-else结构
age = 12
if age < 4:
print("Your admission cast is 0")
elif age < 18:
print("Your admission cast is 25")
else:
print("Your admission cast is 40")
#输出为Your admission cast is 25
4. 使用elif代码块
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
#注:最后结尾用else,不能用elif
price = 20
print(price)
#输出为25
5. 使用if语句处理列表
availiable_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in availiable_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry,we do not have {requested_topping}.")
#输出Adding mushrooms.
#Sorry,we do not have french fries.
#Adding extra cheese.