Python基础(二)

一、if语句

1、条件测试

每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式称为条件测试 。Python根据条件测试的值为True 还是False 来决定是否执行if语句中的代码。如果条件测试的值为True ,Python就执行紧跟在if语句后面的代码;如果 为False ,Python就忽略这些代码。

在Python中检查是否相等时区分大小写。两个大小写不同的值被视为不相等。

如果大小写很重要,这种行为有其优点。但如果大小写无关紧要,只想检查变量的值,可将变量的值转换为小写,再进行比较。

2、检查多个条件

使用 and 检查多个条件

要检查是否两个条件都为True,可使用关键字and 将两个条件测试合而为 一。如果每个测试都通过了,整个表达式就为True ;如果至少一个测试没有通过,整个表达式就为False。

使用or检查多个条件

关键字or也能够让你检查多个条件,但只要至少一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用or 的表达式才为False。

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

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

3、几种不同形式的if语句

简单if语句

最简单的if语句只有一个测试和一个操作

1
2
if conditional_test: 
do something

if-else语句

if-else 语句块类似于简单的 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!")

if-elif-else 结构

Python只执行if-elif-else 结构中的一个代码块。它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。

1
2
3
4
5
6
7
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.")

该结构中可以包含多个elif块。

也可以省略else块。else 是一条包罗万象的语句,只要不满足任何if 或elif 中的条件测试,其中的代码就会执行。这可能引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif 代码块来代替else 代码块。这样就可以肯定,仅当满足相应的条件时,代码才会执行。

测试多个条件

if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。

然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含elif 和else代码块的简单if语句。在可能有多个条件为True且需要在每个条件为True时都采取相应措施时,适合使用这种方法。

4、if语句与列表

确定列表不是空的

1
2
3
4
5
6
7
requested_toppings = [] 
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")

在if 语句中将列表名用作条件表达式时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False。

二、字典

使用字典,能够高效地模拟现实世界中的情形,能够更准确地为各种真实物体建模。

1、使用字典

在Python中, 字典是一系列键值对。每个键都与一个值相关联,你可使用键来访问相关联的值。与键相关联的值可以是数、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。

访问字典中的值

1
2
alien_0 = {'color': 'green'} 
print(alien_0['color'])

字典中可包含任意数量的键值对。

2、字典的一些方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 添加键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

# 定义一个空字典
alien_0 = {}

# 修改字典中的值
alien_0 = {'color': 'green'}
alien_0['color'] = 'yellow'

# 删除键值对
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']

# 由类似对象组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

# 使用get()来访问值
# 使用放在方括号内的键从字典中获取感兴趣的值时,可能会引发问题:如果指定的键不存在就会出错。
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
# 方法get() 的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的

注意 在Python 3.7中,字典中元素的排列顺序与定义时相同。如果将字典打印出来或遍历其元素,将发现元素的排列顺序与添加顺序相同。

注意 删除的键值对会永远消失。

确定需要使用多行来定义字典时,要在输入左花括号后按回车键。在下一行缩进四个空格,指定第一个键值对,并在它后面加上一个逗号。此后再按回车键时,文本编辑器将自动缩进后续键值对,且缩进量与第一个键值对相同。 定义好字典后,在最后一个键值对的下一行添加一个右花括号,并缩进四个空格, 使其与字典中的键对齐。一种不错的做法是,在最后一个键值对后面也加上逗号, 为以后在下一行添加键值对做好准备。

注意 调用get()时,如果没有指定第二个参数且指定的键不存在,Python将返回值None 。这个特殊值表示没有相应的值。None并非错误,而是一个表示所需值不存在的特殊值。

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(f"\nKey: {key}")
print(f"Value: {value}")

for 语句的第二部分包含字典名和方法items(),它返回一个键值对列表。接下来,for 循环依次将每个键值对赋给指定的两个变量。在本例中,使用这两个变量来打印每个键及其相关联的值。

遍历字典中所有的键

1
2
3
4
5
6
7
8
9
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name in favorite_languages.keys():
print(name.title())

遍历字典时,会默认遍历所有的键。因此,如果将上述代码中的: for name in favorite_languages.keys(): 替换为: for name in favorite_languages: 输出将不变。显式地使用方法keys()可让代码更容易理解,你可以选择这样做,但是也可以省略它。

方法keys()并非只能用于遍历:实际上,它返回一个列表,其中包含字典中的所有键。

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

要以特定顺序返回元素,一种办法是在for循环中对返回的键进行排序。为此,可使用函数sorted() 来获得按特定顺序排列的键列表的副本

1
2
3
4
5
6
7
8
9
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")

遍历字典中所有的值

如果主要对字典包含的值感兴趣,可使用方法values()来返回一个值列表,不包含任何键。

1
2
3
4
5
6
7
8
9
10
favorite_languages = { 
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())

这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量重复项。为剔除重复项,可使用集合(set)。集合中的每个元素都必须是独一无二的:

1
2
3
4
5
6
favorite_languages = { 
--snip--
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())

注意  可使用一对花括号直接创建集合,并在其中用逗号分隔元素:

1
languages = {'python', 'ruby', 'python', 'c'}

集合和字典很容易混淆,因为它们都是用一对花括号定义的。当花括号内没有 键值对时,定义的很可能是集合。不同于列表和字典,集合不会以特定的顺序 存储元素。

4、嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套 。你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

字典列表

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)

在字典中存储列表

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

for topping in pizza['toppings']:
print("\t" + topping)

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

注意 列表和字典的嵌套层级不应太多。如果嵌套层级比前面的示例多得多, 很可能有更简单的解决方案。

在字典中存储字典

可在字典中嵌套字典,但这样做时,代码可能很快复杂起来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
users = { 
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},

'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},

}

for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']

print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")

请注意,表示每位用户的字典都具有相同的结构。虽然Python并没有这样的要求, 但这使得嵌套的字典处理起来更容易。倘若表示每位用户的字典都包含不同的键, for循环内部的代码将更复杂。

三、用户输入和 while 循环

1、函数input()

函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python 将其赋给一个变量,以方便你使用。

1
2
message = input("Tell me something, and I will repeat it back to you: ") 
print(message)

函数input() 接受一个参数——要向用户显示的提示(prompt)或说明,让用户知道该如何做。

有时候,提示可能超过一行。例如,你可能需要指出获取特定输入的原因。在这种 情况下,可将提示赋给一个变量,再将该变量传递给函数input() 。这样,即便提 示超过一行,input() 语句也会非常清晰。

1
2
3
4
prompt = "If you tell us who you are, we can personalize the messages you see." 
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")

本例演示了一种创建多行字符串的方式。第一行将消息的前半部分赋给变量prompt 中。在第二行中,运算符+= 在前面赋给变量prompt 的字符串末尾附加一个字符串。

使用int()来获取数值输入

使用函数input() 时,Python将用户输入解读为字符串。为解决这个问题,可使用函数int() ,它让Python将输入视为数值。

1
2
3
4
5
height = int(input("How tall are you, in inches? ") )
if height >= 48:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")

2、求模运算符

处理数值信息时, 求模运算符 (%)是个很有用的工具,它将两个数相除并返回余数。

求模运算符不会指出一个数是另一个数的多少倍,只指出余数是多少。

如果一个数可被另一个数整除,余数就为0,因此求模运算将返回0。可利用这一点 来判断一个数是奇数还是偶数

1
2
3
4
5
6
number = input("Enter a number, and I'll tell you if it's even or odd: ") 
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")

3、while循环

for 循环用于针对集合中的每个元素都执行一个代码块,而while 循环则不断运行,直到指定的条件不满足为止。

让用户选择何时退出

1
2
3
4
5
6
prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)

使用标志退出

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。这样,在while语句中就只需检查一个条件:标志的当前值是否为True 。

1
2
3
4
5
6
7
8
9
10
prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. "

active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)

使用 break 退出循环

要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如 何,可使用break 语句。

在循环中使用 continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句,它不像break 语句那样不再执行余下的代码并退出整个循环。

1
2
3
4
5
6
7
current_number = 0 
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue

print(current_number)

4、使用 while 循环处理列表和字典

在列表之间移动元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 首先,创建一个待验证用户列表 
# 和一个用于存储已验证用户的空列表。
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# 验证每个用户,直到没有未验证用户为止。
# 将每个经过验证的用户都移到已验证用户列表中。
while unconfirmed_users:
current_user = unconfirmed_users.pop()

print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)

# 显示所有已验证的用户。
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

删除为特定值的所有列表元素

1
2
3
4
5
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)

使用用户输入来填充字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
responses = {} 

# 设置一个标志,指出调查是否继续。
polling_active = True

while polling_active:
# 提示输入被调查者的名字和回答。
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")

# 将回答存储在字典中。
responses[name] = response

# 看看是否还有人要参与调查。
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False

# 调查结束,显示结果。
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")