第五章 if 语句
和 C 区别,条件语句不带括号(),但是后面多了个冒号:
if 内的语句不需要大括号,但是要缩进。
5.2 条件测试
cars = [‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]
for car in cars:
if car == ‘bmw’: # 后面有冒号“:”,区别于c语言
print(car.upper())
else:
print(car.title())
5.2.1 检查是否相等
car = ‘bmw’
car == ‘bmw’
True
5.2.2 检查是否相等时不考虑大小写
在Python中检查是否相等时区分大小写
5.2.3 检查是否不相等
requested_topping = ‘mushrooms’
if requested_topping != ‘anchovies’:
print(“Hold the anchovies!”)
5.2.4 比较数字
age = 18
age == 18
True
5.2.5 检查多个条件
- 使用and 检查多个条件
要检查是否两个条件都为True ,可使用关键字and 将两个条件测试合而为一
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21 #相当于C中的 &&
False
- 使用or 检查多个条件
关键字or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1 >= 21 #相当于C中的 ||
True
5.2.6 检查特定值是否包含在列表中
requested_toppings = [‘mushrooms’, ‘onions’, ‘pineapple’]
‘mushrooms’ in requested_toppings
True
5.2.7 检查特定值是否不包含在列表中
使用关键字 not in
banned_users = [‘andrew’, ‘carolina’, ‘david’]
user = ‘marie’
if user not in banned_users:
print(user.title() + “, you can post a response if you wish.”)
Marie, you can post a response if you wish.
5.2.8 布尔表达式
布尔表达式的结果要么为True ,要么为False
5.3 if 语句
5.3.1 简单的if 语句
if conditional_test:
do something
如:
age = 19
if age >= 18:
print(“You are old enough to vote!”)
You are old enough to vote!
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 as 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 结构
于上类比
age = 12
if age < 4:
print(“Your admission cost is $0.”)
elif age < 18:
print(“Your admission cost is $5.”)
else:
print(“Your admission cost is $10.”)
Your admission cost is $5.
5.3.4 使用多个elif 代码块
类比。。。
5.4 使用if 语句处理列表
requested_toppings = [‘mushrooms’, ‘green peppers’, ‘extra cheese’]
for requested_topping in requested_toppings:
print(“Adding " + requested_topping + “.”)
print(”\nFinished making your pizza!")
5.4.2 确定列表不是空的
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(“Adding " + requested_topping + “.”)
print(”\nFinished making your pizza!")
else:
print(“Are you sure you want a plain pizza?”)
5.4.3 使用多个列表
available_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 available_toppings:
print(“Adding " + requested_topping + “.”)
else:
print(“Sorry, we don’t have " + requested_topping + “.”)
print(”\nFinished making your pizza!”)