Python编程:从入门到实践 第7章课后习题
7-8题不太懂。
7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。
dealer = input('What sort of car would you like?\n')
print('Let me see if I can find you a', dealer.title() + '.')
7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。
reserve = input('How many people are coming?\n')
reserve = int(reserve)
if reserve > 8:
print('Sorry, not available.')
elif reserve <= 8:
print('Welcome.')
7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是10的整数倍。
number = input('Enter a number, please:\n')
number = int(number)
compare = number % 10
if compare ==0:
print(number,"is a multiple of 10!")
else:
print(number, "is NOT a multiple of 10 and it has a reminder of", compare, '.')
7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit' 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
prompt = '\nTell us what do you want for your toppings.'
prompt += '\nEnter quit to quit.\n'
toppings = ''
while toppings != 'quit':
toppings = input(prompt)
if toppings != 'quit':
print('we will add', toppings, 'to your pizza.')
7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
prompt = "\nTell us your age:"
prompt += "\nEnter 'quit' to end the program.\n\t"
while True:
age = input(prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print('For children under 3, Free.')
elif age <= 12:
print('10 dollars for children betwee 3 and 12.')
elif age >12:
print('15 dollars for people over 12.')
while true是一定要用break断开的,否则一直循环。
7-6 三个出口:以另一种方式完成练习7-4或练习7-5,在程序中采取如下所有做法。
- 在while 循环中使用条件测试来结束循环。 7-5 重写:
prompt = "\nTell us your age:"
prompt += "\nEnter 'quit' to end the program.\n\t"
age = ''
while age != 'quit':
age = input(prompt)
if int(age) < 3:
print('For children under 3, Free.')
elif int(age) <= 12:
print('10 dollars for children betwee 3 and 12.')
elif int(age) >12:
print('15 dollars for people over 12.')
else:
print('thank you')
这段代码输入数字正常,但如果输入quit报错:if int(age) < 3: ValueError: invalid literal for int() with base 10: 'quit'
似乎是因为有int(age),所以输入字母就报错了。
- 使用变量active 来控制循环结束的时机。 7-5 重写:
prompt = "\nTell us your age:"
prompt += "\nEnter 'quit' to end the program.\n\t"
active = True
while active:
age = input(prompt)
if age != 'quit':
age = int(age)
if age < 3:
print('For children under 3, free.')
elif age <= 12:
print('10 dollars for children betwee 3 and 12.')
elif age >12:
print('15 dollars for people over 12.')
else:
active = False
- 使用break 语句在用户输入'quit' 时退出循环。
同7-5。这里改用
continue写一段吧。假设3岁以下和65以上都免费。
age = 0
while age < 99:
age += 1
if age < 3 or age > 65:
continue
if age < 12:
print(age, '10 for 3 to 12.')
7-7 无限循环 :编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl+C,也可关闭显示输出的窗口)。
age = 1
while age != 0:
age += 1 #刚写成了age += age,直接把spyder弄司机了。。囧。。
print(age)
7-8 熟食店:创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['tuna','egg','vege','salami']
finished_sandwiches=[]
while sandwich_orders:
processing = sandwich_orders.pop()
print('I am making your', processing, 'sandwich.')
finished_sandwiches.append(processing)
从被选列表开始while,然后加一个过渡变量,然后一项一项处理。
但一个触动灵魂的问题,教材里面说:
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
但这个问题有一个新的列表了finished_sandwiches,不还是可以用for吗?包括教材里面的例子也能用for。
sandwich_orders = ['tuna','egg','vege','salami']
finished_sandwiches=[]
for x in sandwich_orders:
print('I am making your', x, 'sandwich.')
finished_sandwiches.append(x)
for x in finished_sandwiches:
print(x.title())
sandwich_orders.clear()
while打印出来的是:
I am making your salami sandwich.
I am making your vege sandwich.
I am making your egg sandwich.
I am making your tuna sandwich.
Salami
Vege
Egg
Tuna
for打印出来的是:
I am making your tuna sandwich.
I am making your egg sandwich.
I am making your vege sandwich.
I am making your salami sandwich.
Tuna
Egg
Vege
Salami
两者的区别在于pop从后往前,for从前往后,外加pop将原列表清空。但for的最后一句sandwich_orders.clear()也是清空,完全一样的效果。两个的区别在什么地方?
注:书中的例子照抄于此,并用for改写:
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("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())
print("-----my method using 'for'-----")
print('----两者除顺序和列表外无不同-----')
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
for current_user in unconfirmed_users:
print("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())
7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习7-8而创建的列表sandwich_orders ,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while循环将列表sandwich_orders中的'pastrami' 都删除。确认最终的列表finished_sandwiches中不包含'pastrami'。
sandwich_orders = ['tuna','pastrami','egg','pastrami','vege','pastrami','salami']
finished_sandwiches=[]
print(sandwich_orders)
print("Pastrami is out of order.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
while sandwich_orders:
processing = sandwich_orders.pop()
print('I am making your', processing, 'sandwich.')
finished_sandwiches.append(processing)
print(finished_sandwiches)
这个好像用for比较麻烦了,因为涉及到对原始的list的修改。
7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one placein the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
surveys = {}
polling_action = True
while polling_action:
name = input("\t'What's your name?")
result = input("\tIf you could visit one placein the world, where would you go?")
surveys[name] = result
repeat = input('Would you like another person to respond? (yes/no)')
if repeat == 'no':
polling_action = False
for x, y in surveys.items():
print(x.title()+' ''would like to go '+y.title()+'.')
这里要注意,survey这个字典,就{姓名:答案},surveys[name] = result,不是{name:xxx},{answer:xxx}的格式。刚开始写成了:
surveys['name'] = name
surveys['ansewer'] = result
这一篇。。。有点难,明天还要再看一下~~~