第五章 if语句
5.1 一个简单示例
输入:
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper()) # 若是,首字母大写方式打印
else:
print(car.title()) # 若不是,全大写方式打印
输出:
Audi
BMW
Subaru
Toyota
5.2 条件测试
5.2.1 检查是否相等
5.2.2 检查是否相等时忽略大小写
# 检查是否相等
car = 'bmw' # 赋值
car == 'bmw' # 相等运算符,检查是否相等
True
car = 'audi' # 赋值
car == 'bmw' # 相等运算符,检查是否相等
False
#检查是否相等时忽略大小写
car = 'Audi' #区分大小写
car == 'audi'
False
car = 'Audi' #转换为小写后再进行比较
car.lower() == 'audi'
Ture
car = 'Audi' #lower()并不会关联到car的值
car.lower() == 'audi'
Ture
car
'Audi'
5.2.3 检查是否不相等
输入:
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
输出:
Hold the anchovies!
5.2.4 数值比较
age = 18
age == 18
Ture
age = 19
age < 21
True
age <= 21
True
age > 21
False
age >=21
False
输入:
answer = 17
if answer != 42:
print("That is not the correct answer.Please try again!")
输出:
That is not the correct answer.Please try again!
5.2.5 检查多个条件
# 使用and检查多个条件
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21
False
age_1 = 22
age_0 >= 21 and age_1 >= 21
True
# 使用or检查多个条件
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1 >= 21
True
age_0 = 18
age_0 >= 21 or age_1 >= 21
False
# 检查特定值是否包含在列表中 in
requested_toppings = ['mushroom','onions','pineapple']
'mushroom' in requested_toppings
True
'pepperoni' in requested_toppings
False
输入:
# 检查特定值是否不包含在列表中 not in
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()},you can post a response if you wish.")
输出:
marie,you can post a response if you wish.
5.3 if语句
5.3.1 简单的if语句
if conditional_test:
do something
输入:
age = 19
if age >= 18:
print(“You are old enough to votel!")
输出:
You are old enough to votel!
5.3.2 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.")
print("Please register to vote as soon you turn 18!")
输出:
Sorry,you are too young to vote.
Please register to vote as soon as you turn 18!
5.3.3 if-elif-else结构
4岁以下免费,4~18岁收费25美元,18岁(含)以上收费40美元。
方式一:
输入:
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
输出:
Your admission cost is $25.
方式二,以更为简洁的方式。
输入:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ${price}.")
输出:
Your admission cost is $25.
5.3.4 使用多个elif代码块
下面假设对于65岁(含)以上的老人,可半价(即20美元)购买门票:
输入:
age = 80
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.")
输出:
Your admission cost is 20.
5.3.5 省略else代码块
Python并不要求if-elif结构后面必须有else代码块。
输入:
age = 80
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else age > 65:
price = 20
print(f"Your admission cost is ${price}.")
输出:
Your admission cost is 20.