内容包括:
- 条件语句
- 布尔表达式
- For 和 While 循环
- Break 和 Continue
- Zip 和 Enumerate
- 列表推导式
条件语句
缩进
一些其他语言使用花括号来表示代码块从哪儿开始,从哪儿结束。在 Python 中,我们使用缩进来封装代码块
。例如,if 语句使用缩进告诉 Python 哪些代码位于不同条件语句里面,哪些代码位于外面。
在 Python 中,缩进通常是四个空格一组
。请严格遵守该惯例
,因为更改缩进会完全更改代码的含义。
age = 35
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
concession_ticket = 1.25
adult_ticket = 2.50
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
print(message)
# 输出
Somebody who is 35 years old will pay $2.5 to ride the bus.
条件布尔表达式
复杂的布尔类型
If 语句有时候会使用更加复杂的条件布尔表达式。可能包括多个比较运算符、逻辑运算符,甚至包括算式
。
if 18.5 <= weight / height**2 < 25:
print("BMI is considered 'normal'")
if is_raining and is_sunny:
print("Is there a rainbow?")
if (not unsubscribed) and (location == "USA" or location == "CAN"):
print("send email")
无论是简单还是复杂的条件,if 语句中的条件都必须是结果为
True 或 False 的布尔表达式
,该值决定了 if 语句中的缩进代码块是否执行
。
正反面示例
1.请勿使用 True 或 False 作为条件
# Bad example
if True:
print("This indented code will always get run.")
虽然“True”是一个有效的布尔表达式,但不是有用的条件
,因为它始终为 True,因此缩进代码将始终运行
。同样,if False 也不应使用,该 if 语句之后的语句将从不运行。
# Another bad example
if is_cold or not is_cold:
print("This indented code will always get run.")
同样,使用你知道将始终结果为 True 的条件
(例如上述示例)也是毫无用途的。布尔表达式只能为 True 或 False,因此 is_cold 或 not is_cold 将始终为 True,缩进代码将始终运行。
2.在使用逻辑运算符编写表达式时,要谨慎
# Bad example
if weather == "snow" or "rain":
print("Wear boots!")
这段代码在 Python 中是有效的,但不是布尔表达式,虽然读起来像。原因是 or运算符右侧的表达式 "rain" 不是布尔表达式
,它是一个字符串。稍后我们将讨论当你使用非布尔型对象替换布尔表达式时,会发生什么。
3. 请勿使用 == True
或 == False
比较布尔变量
这种比较没必要,因为布尔变量本身是布尔表达式
。
# Bad example
if is_cold == True:
print("The weather is cold!")
这是一个有效的条件,但是我们可以使用变量本身作为条件
,使代码更容易读懂
,如下所示。
# Good example
if is_cold:
print("The weather is cold!")
如果你想检查布尔表达式是否为 False,可以使用 not 运算符
。
真假值测试
如果我们在 if 语句中使用非布尔对象
代替布尔表达式,Python 将检查其真假值
,判断是否运行缩进代码
。默认情况下,Python 中对象的真假值被视为 True
,除非在文档中被指定为 False。
以下是在 Python 中被视为 False 的大多数内置对象:
- 定义为 false 的常量:
None
和False
- 任何数字类型的零:
0
、0.0
、Decimal(0)
、Fraction(0, 1)
- 空序列和空集合:
""
、()
、[ ]
、{ }
、set()
、range(0)
points = 60
prize = None
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a water-thin mint"
elif points >= 181:
prize = "a penguin"
if prize:
result = "Congratulations! You have won " + prize + "!"
else:
result = "Oh dear, no prize this time."
print(result)
# 输出
Oh dear, no prize this time.