参考书籍:《Python编程 从入门到实践》
1. 条件测试
if语句的核心都是一个值为True或False的表达式,这种表达式称为条件表达式
1.1 单个条件测试
- 相等:
==
- 不相等:
!=
- 其他:
>
、>=
、<
、<=
1.2 多个条件测试
and
、or
多个条件时,每个测试表达式添加括号更易阅读
1.3 特定值是否包含在列表中
in
、not in
1.4 布尔表达式
布尔表达式就是条件表达式的别名,其结果要么是True,要么是False。
2. if语句的结构
2.1 简单if结构
age = 19
if age >= 18:
print("You are old enough to vote!")
2.2 if-else结构
age = 17
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote.")
2.3 if-elif-else结构
age = 14
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.")
elif
代码块可以多次使用else
代码块可以省略
2.4 测试多个条件
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
if-elif-else
结构中只会执行一个代码块;如果要运行多个代码块就需要使用一系列连续的if
语句。
3. 用if语句处理列表
3.1 检查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
3.2 确定不是空列表
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
else:
print("Are you sure you want a plan pizza?")
if语句中将列表名用在条件表达式中时,列表不为空时返回Ture,否则为False。
网友评论