第五章
5-1 条件测试
编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。
print(1 == '1')
print(49 == '1')
因为python中的变量可以重新定义类型,所以第一句可能是True?
因为‘1’的ASCII码是49,所以第二句可能是True?
运行结果:
False
False
这说明python中的变量在比较中是不能重新定义类型的。同时,与C不同,python没有字符这种类型。
类型不同的相同数可以比较吗?整除与浮点数除法不同吗?浮点数运算有误差吗?
a = 3
b = 3.00
print( a == b )
print( 1 // b == 1 / a )
print( 0.2 + 0.1 != 0.3)
运行结果:
True
False
True
这说明python中的变量类型不同的相同数是可以比较的。同时,与C不同,python3.0中整除是//,除法是/。浮点数运算有舍入误差!
range用法:
print( 1 in range(1,10))
print( 10 in range(1,10))
运行结果:
True
False
列表用法1:
list1 = ['haha','hei']
list2 = list1[:]
print(list1 == list2)
list2 = list1.reverse()
print(list1 == list2)
运行结果:
True
False
这里需要注意,复制列表不能直接赋值。
列表用法2:
car1 = ['subaru','audi']
car2 = car1
car2 = ['toyota','bmw']
print(car1 == car2)
car2 = car1
car2[0] = 'toyota'
print(car1 == car2)
运行结果:
False
True
5-2 更多的条件测试
你并非只能创建10个测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到
conditional_tests.py中。对于下面列出的各种测试,至少编写一个结果为True和False的测试。
- 检查两个字符串相等和不等。使用函数lower()的测试。
- 检查两个数字相等、不等、大于、小于、大于等于和小于等于。 使用关键字and和or的测试。
- 测试特定的值是否包含在列表中。
- 测试特定的值是否未包含在列表中。
str = "HAHA"
print(str > str.lower())
print(1 == 0 or 1 != 0)
print(1 > 0 and 1 < 0)
print(1 in range(1,10))
print(10 not in range(1,10))
5-3 外星人颜色#1
假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为’green’、’yellow’ 或’red’。
- 编写一条if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了5个点。
- 编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
color = ['green','yellow','red']
alien_color = color[0]
if alien_color == 'green':
print("Get 5 points")
5-4 外星人颜色#2
像练习5-3那样设置外星人的颜色,并编写一个if-else 结构。
- 如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了5个点。
- 如果外星人不是绿色的,就打印一条消息,指出玩家获得了10个点。
- 编写这个程序的两个版本,在一个版本中执行if 代码块,而在另一个版本中执行else 代码块。
color = ['green','yellow','red']
alien_color = color[0]
if alien_color == 'green':
print("Get 5 points")
else:
print("Get 10 points")
5-5 外星人颜色#3
将练习5-4中的if-else 结构改为if-elif-else 结构。
- 如果外星人是绿色的,就打印一条消息,指出玩家获得了5个点。
- 如果外星人是黄色的,就打印一条消息,指出玩家获得了10个点。
- 如果外星人是红色的,就打印一条消息,指出玩家获得了15个点。
- 编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
color = ['green','yellow','red']
alien_color = color[0]
if alien_color == 'green':
print("Get 5 points")
elif alien_color == 'yellow':
print("Get 10 points")
elif alien_color == 'red':
print("Get 15 points")
5-6 人生的不同阶段
设置变量age 的值,再编写一个if-elif-else 结构,根据age 的值判断处于人生的哪个阶段。
- 如果一个人的年龄小于2岁,就打印一条消息,指出他是婴儿。
- 如果一个人的年龄为2(含)~4岁,就打印一条消息,指出他正蹒跚学步。
- 如果一个人的年龄为4(含)~13岁,就打印一条消息,指出他是儿童。
- 如果一个人的年龄为13(含)~20岁,就打印一条消息,指出他是青少年。
- 如果一个人的年龄为20(含)~65岁,就打印一条消息,指出他是成年人。
- 如果一个人的年龄超过65(含)岁,就打印一条消息,指出他是老年人。
import random
age = random.randint(0,100)
if age >= 0 and age < 2:
print("You are a baby.")
elif age >= 2 and age < 4 :
print("You are a toddle.")
elif age >= 4 and age < 13 :
print("You are an enfant.")
elif age >= 13 and age < 20 :
print("You are a teenager.")
elif age >= 20 and age < 65 :
print("You are an adult.")
elif age >= 65 :
print("You are an old people.")
5-7 喜欢的水果
创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if 语句,检查列表中是否包含特定的水果。
- 将该列表命名为favorite_fruits ,并在其中包含三种水果。
- 编写5条if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如“You really like bananas!”。
favorite_fruits = ['apple','orange','pineapple']
fruits = ['pear','peach','apple','grape','banana','cherry','watermelon','pomegranate']
for fruit in fruits:
if fruit in favorite_fruits:
print("You really like " + fruit)
5-8 以特殊方式跟管理员打招呼
创建一个至少包含5个用户名的列表,且其中一个用户名为’admin’ 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。
- 如果用户名为’admin’ ,就打印一条特殊的问候消息,如“Hello admin, would you like to see astatus report?”。
- 否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
users = ['admin','Peter','Jerry','Alice','Tew']
for user in users:
if user == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print("Hello " + user + ", thank you for logging in again")
5-9 处理没有用户的情形
在为完成练习5-8编写的程序中,添加一条if 语句,检查用户名列表是否为空。
- 如果为空,就打印消息“We need to find some users!”。
- 删除列表中的所有用户名,确定将打印正确的消息。
users = []
if not users:
print("We need to find some users!")
5-10 检查用户名
按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
- 创建一个至少包含5个用户名的列表,并将其命名为current_users 。
- 再创建一个包含5个用户名的列表,将其命名为new_users ,并确保其中有一两个用户名也包含在列表current_users 中。
- 遍历列表new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
- 确保比较时不区分大消息;换句话说,如果用户名’John’ 已被使用,应拒绝用户名’JOHN’。
current_users = ['Uchin','Peter','George','Alice','Tew','John']
new_users = ['Kevin','Louis','JOHN','Henry','Benjamin']
tmps = [current_user.lower() for current_user in current_users]
for new_user in new_users:
if new_user.lower() in tmps :
print(new_user + " has been used.You need to enter another username.")
else :
print(new_user + " is not used.")
5-11 序数
序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。
- 在一个列表中存储数字1~9。
- 遍历这个列表。
- 在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序数都独占一行。
numbers = list(range(1,9))
for number in numbers:
print(number,end = '')
if number == 1:
print("st")
elif number == 2:
print("nd")
elif number == 3:
print("rd")
else:
print("th")
本章注意点
- Python将在列表至少包含一个元素时返回True ,并在列表为空时返回False
第六章
6-1 人
使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中的每项信息都打印出来。
familiar_man = {
'first_name': 'Tew',
'last_name': 'Wee',
'age': 20,
'city': 'Mount Air',
}
for key, value in familiar_man.items():
print(key + ': ', end = '')
print(value)
6-2 喜欢的数字
使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_numbers = {'Heidi': 13,
'Ingrid': 66,
'Ishara': 77,
'Irene': 295,
'Ivy': 1,
}
for key, value in favorite_numbers.items():
print(key + ':', value)
6-3 词汇表
Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
- 想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
- 以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n )插入一个空行,然后在下一行以缩进的方式打印词汇的含义。
word_list = {'dict': "Associative array (or dictionary) of key and value pairs",
'set': "Unordered set, contains no duplicates; can contain mixed types, if hashable",
'list': "List, can contain mixed types, mutable",
'tuple': "Can contain mixed types, immutable",
'lambda expression': "a function definition that is not bound to an identifier",
}
print('dict' + ': ' +
"Associative array (or dictionary) of key and value pairs\n" +
'set' + ': ' +
"Unordered set, contains no duplicates; can contain mixed types, if hashable\n" +
'list' + ': ' +
"List, can contain mixed types, mutable\n" +
'tuple' + ': ' +
"Can contain mixed types, immutable\n" +
'lambda expression' + ':' +
"a function definition that is not bound to an identifier")
6-4 词汇表2
既然你知道了如何遍历字典,现在请整理你为完成练习6-3而编写的代码,将其中的一系列print 语句替换为一个遍历字典中的键和值的循环。确定该循环正确无误后,再在词汇表中添加5个Python术语。当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。
word_list = {'dict': "Associative array (or dictionary) of key and value pairs",
'set': "Unordered set, contains no duplicates; can contain mixed types, if hashable",
'list': "List, can contain mixed types, mutable",
'tuple': "Can contain mixed types, immutable",
'lambda expression': "A function definition that is not bound to an identifier",
'if': "If conditionally executes a block of code, along with else and elif",
'for': "For iterates over an iterable object, capturing each element to a local variable for use by the attached block",
'while': "It executes a block of code as long as its condition is true",
'try': "It allows exceptions raised in its attached code block to be caught and handled by except clauses; it also ensures that clean-up code in a finally block will always be run regardless of how the block exits",
'def': "It defines a function or method",
}
for k, v in word_list.items():
print("\n" + k + ": " + v)
6-5 河流
创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是’nile’: ‘egypt’ 。
- 使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
- 使用循环将该字典中每条河流的名字都打印出来。
- 使用循环将该字典包含的每个国家的名字都打印出来。
rivers = {'Nile': 'Egypt', 'Yangtze': 'China', 'Mississippi': 'US'}
for k, v in rivers.items():
print("The " + k + " runs through " + v)
for river in rivers.keys():
print(river)
for country in rivers.values():
print(country)
6-6 调查
在6.3.1节编写的程序favorite_languages.py中执行以下操作。
- 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
- 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
members = ['jen', 'andy', 'sarah', 'mary', 'edward', 'phil']
for member in members:
if member in favorite_languages:
print("Thank you for participation in the survey, " + member)
else:
print("We sincerely invite you to participate in the investigation, " + member)
6-7 人
在为完成练习6-1而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
people = [
{
'first_name': 'Tew',
'last_name': 'Wee',
'age': 20,
'city': 'Mount Air',
},
{
'name': 'Unknown',
'gender': 'Male',
'age': 35,
'country': 'China',
},
{
'planet': 'X-galaxy',
'structure': 'Nothingness'
},
]
for person in people:
print(person)
6-8 宠物
创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
miao = {'type': 'cat', 'master': 'Lee'}
wang = {'type': 'dog', 'master': 'Tew'}
gua = {'type': 'frog', 'master': 'Jim'}
pets = [miao, wang, gua]
for pet in pets:
print(pet)
6-9 喜欢的地方
创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
'Lee': ['Macau, China', 'Biloxi, Mississippi', 'Detroit, Michigan',],
'Tew': ['Las Vegas', 'Uncasville, Connecticut', 'Atlantic City, New Jersey',],
'Jim': ['Hobart, Tasmania', 'Almond Beach, Belize', 'Sauble Beach in Ontario, Canada',],
}
for k, v in favorite_places.items():
print('\n' + k + "'s favorite places are:")
for place in v:
print(place)
6-10 喜欢的数字
修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
favorite_numbers = {'Heidi': 13,
'Ingrid': [66, 9],
'Ishara': [77, 90, 32],
'Irene': [295, 20, 13],
'Ivy': [1, 3, 9],
}
for key, value in favorite_numbers.items():
print(key + ':', value)
6-11 城市
创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'Alexandria': {
'country': 'Egypt',
'population': 5172387,
'fact': 'is the second-largest city in Egypt and a major economic centre, extending about 32 km (20 mi) along the coast of the Mediterranean Sea in the north central part of the country.',
},
'Bogota': {
'country': 'Colombia',
'population': 8080734,
'fact': 'is the capital and largest city of Colombia administered as the Capital District, although often thought of as part of Cundinamarca.',
},
'Dallas': {
'country': 'United States',
'population': 1197816,
'fact': 'is a city in the U.S. state of Texas.',
},
}
for city_name, city_info in cities.items():
print(city_name)
for k, v in city_info.items():
print('\t' + k + ': ', end = '')
print(v)
print('\n')