Python3 学习笔记(六)用户输入和while循环
参考书籍《Python编程:从入门到实践》【美】Eric Matthes
让用户输入一个数字,并指出这个数字是否是10的整数倍。
number = input('Enter a number: ')
number = int(number)
if number % 10 == 0:
print('Yes')
else:
print('No')
有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。并在用户输入’quit’ 时结束循环
prompt = 'How old are you?'
while True:
age = input(prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print('free')
elif age < 12:
print('$10')
else:
print('$15')
创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['tuna', 'chesse', 'pastrami']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print('I made your ' + sandwich + ' sandwich')
finished_sandwiches.append(sandwich)
print('All sandwiches have been made:')
for sandwich in finished_sandwiches:
print(sandwich)
创建的列表sandwich_orders ,并确保’pastrami’ 在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders 中的’pastrami’ 都删除。确认最终的列表finished_sandwiches 中不包含’pastrami’ 。
sandwich_orders = ['pastrami', 'tuna', 'pastrami', 'chesse', 'pastrami']
print('All pastrami sandwiches have been sold:')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
result = {}
active = True
while active:
name = input('What is your name?')
place = input('If you could visit one place in the world, where would you go?')
result[name] = place
repeate = input('Would you like to let another person respond? (yes/ no)')
if repeate == 'no':
active = False
print('The result is:')
for name, place in result.items():
print(name + ' want to visit ' + place)