1
2
3
4
5
6
7
# 先检查当前的汽车名是否是'bmw'
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota

条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为 条件测试
==相等运算符在它两边的值相等时返回True,需考虑大小写,可以比较数字
!=要判断两个值是否不等,可结合使用惊叹号和等号

1
2
car = 'bmw'
car == 'bmw'
True
1
car
'bmw'
1
2
age = 18
age ==18
True

检查多个条件

  1. 使用and检查多个条件
  2. 使用or检查多个条件
1
2
3
4
# 使用and检查多个条件
age_0 = 18
age_1 = 20
age_0 >= 19 and age_1 >= 19
False
1
2
age_0 = 22
age_0 >= 19 and age_1 >= 19
True
1
2
3
age_0 = 22 
age_1 = 18
age_0 >= 21 or age_1 >= 21
True
1
2
age_0 = 18 
age_0 >= 21 or age_1 >= 21
False

检查特定值是否包含在列表中

1
2
requested_toppings = ['mushrooms', 'onions', 'pineapple'] 
'mushrooms' in requested_toppings
True
1
2
requested_toppings = ['mushrooms', 'onions', 'pineapple'] 
'pepperoni' in requested_toppings
False

检查特定值是否不包含在列表中

1
2
3
4
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.

布尔表达式

不过是条件测试的别名
只有TrueFalse

if语句


1
2
if conditional_test:    
do something
1
2
3
4
# 简单例子
age = 19
if age >= 18:
print("You are old enough to vote!")
You are old enough to vote!

if-else语句

1
2
3
4
5
6
7
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!

if-elif-else 结构

1
2
3
4
5
6
7
8
age = 12 
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
Your admission cost is $5.

使用多个 elif 代码块

1
2
3
4
5
6
7
8
9
10
age = 12 
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
Your admission cost is $5.

省略 else 代码块

1
2
3
4
5
6
7
8
9
10
age = 12 
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
Your admission cost is $5.

测试多个条件

1
2
3
4
5
6
7
8
9
10
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!")
Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

总之,如果你只想执行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句

使用if语句处理列表


  1. 检查特殊元素
  2. 确认列表不是空的
  3. 使用多个列表
1
2
3
4
5
6
7
8
# 加料过程中某一原料不够,但仍有人点菜
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!")
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!
1
2
3
4
5
6
7
8
# 列表为空
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?")
Are you sure you want a plain pizza?
1
2
3
4
5
6
7
8
9
10
# 使用多个列表
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!")
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

诸如==、>=和<=等比较运算符两边各添加一个空格

小结


在本章中,你学习了如何编写结果要么为Ture要么为False的条件测试。你学习了如何编写简单的if语句、if-else语句和if-elif-else结构。在程序中,你使用了这些结构来测试特定的条件,以确定这些条件是否满足

1
2
3
4
# 简单例子
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
green
5

字典是一系列键—值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。
事实上,可将任何Python对象用作字典中的值。
字典用放在花括号{}中的一系列键—值对表示
键和值之间用冒号分隔,而键—值对之间用逗号分隔

1
2
3
# 访问字典中的值,依次指定字典名和放在方括号内的键
alien_0 = {'color': 'green'}
print(alien_0['color'])
green
1
2
3
alien_0 = {'color': 'green', 'points': 5} 
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
You just earned 5 points!

字典操作


添加键—值对

1
2
3
4
5
alien_0 = {'color': 'green', 'points': 5} 
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

创建一个空字典

1
2
3
4
5
alien_0 = {} 
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{}
{'x_position': 0, 'y_position': 25}

修改字典中的值

1
2
3
4
5
# 修改外星人的颜色
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
The alien is green.
The alien is now yellow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'fast'} 
print("Original x-position: " + str(alien_0['x_position']))
# 向右移动外星人
# 据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# 这个外星人的速度一定很快
x_increment = 3
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
Original x-position: 0
New x-position: 3

删除键—值对

1
2
3
4
alien_0 = {'color': 'green', 'points': 5} 
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}

确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键—值对,并在它后面加上一个逗号。此后你再次按回车键时,文本编辑器将自动缩进后续键—值对,且缩进量与第一个键—值对相同。
演示了如何将较长的print语句分成多行。单词print比大多数字典名都短,因此
让输出的第一部分紧跟在左括号后面是合理的。请选择在合适的地方拆分要打印的内容,并在第一行末尾加上一个拼接运算符(+)

遍历字典


  1. 遍历字典中的所有键值对
  2. 遍历字典中的所有键
  3. 遍历字典中的所有值

遍历所有的键值对

1
2
3
4
5
6
7
8
user_0 = { 
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi
1
2
3
4
5
6
7
8
9
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

遍历所有的键

遍历字典时,会默认遍历所有的键
keys()
实际上,它返回一个列表,其中包含字典中的所有键

1
2
3
4
5
6
7
8
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen
Sarah
Edward
Phil
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())

if name in friends:
print("Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!

按顺序遍历字典中的所有键

sorted

1
2
3
4
5
6
7
8
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name)
edward
jen
phil
sarah

遍历字典中的所有值

1
2
3
4
5
6
7
8
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for value in favorite_languages.values():
print(value)
python
c
ruby
python

通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合

1
2
3
4
5
6
7
8
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for value in set(favorite_languages.values()):
print(value)
ruby
c
python

嵌套


字典列表

1
2
3
4
5
6
7
8
# 如何管理成群结队的外星人
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 使用range()生成了30个外星人
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
aliens.append(new_alien)

# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("...")

# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

在字典中存储列表

1
2
3
4
5
6
7
8
# 存储所点比萨的信息
pizza = {'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'], }
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
You ordered a thick-crust pizza with the following toppings:
    mushrooms
    extra cheese

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表

1
2
3
4
5
6
7
8
9
10
favorite_languages = { 
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
Jen's favorite languages are:
    Python
    Ruby

Sarah's favorite languages are:
    C

Edward's favorite languages are:
    Ruby
    Go

Phil's favorite languages are:
    Python
    Haskell

在字典中存储字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
users = { 
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton

Username: mcurie
    Full name: Marie Curie
    Location: Paris

小结

如何定义字典,以及如何使用存储在字典中的信息;如何访问和修改字典中的元素,以及如何遍历字典中的所有信息;如何遍历字典中所有的键值对、所有的键和所有的值;如何在列表中嵌套字典、在字典中嵌套列表以及在字典中嵌套字典