该章主要讲述了input()方法实现用户和程序之间的交互。同时还讲述了另外一种循环体——while()以及退出循环的方法——braek和跳过循环的方法——continue。
7-2 餐馆订位
题目描述:
编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。
INPUT:
7
12
OUTPUT:
Yeah, there is an empty table.
Sorry, there isn't empty table.
代码展示:
num = int(input("How many people do you have for dinner?\n"))
if num > 8:
print("Sorry, there isn't empty table.")
else:
print("Yeah, there is an empty table.")
7-3 10的整数倍
题目描述:
让用户输入一个数字,并指出这个数字是否是10的整数倍。
INPUT:
12
20
OUTPUT:
It isn't any times of 10.
This number is 2 times of 10.
代码展示:
num = int(input("Please input a number.\n"))
if num % 10:
print("It isn't any times of 10.")
else:
print("This number is " + str(int(num / 10)) + " times of 10.")
7-4 比萨配料
题目描述:
编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit' 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
INPUT:
pork
beef
seafood
quit
OUTPUT:
what would you add for pizza?
Okay!We will add pork in your pizza!
what would you add for pizza?
Okay!We will add beef in your pizza!
what would you add for pizza?
Okay!We will add seafood in your pizza!
what would you add for pizza?
代码展示:
food = input("what would you add for pizza?\n")
while food != 'quit':
print("Okay!We will add " + food + " in your pizza!")
food = input("what would you add for pizza?\n")
7-5 电影票
题目描述:
有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
INPUT:
16
3
9
2
quit
OUTPUT:
How old are you?
You should pay 12 dollars!
How old are you?
You should pay 10 dollars!
How old are you?
You should pay 10 dollars!
How old are you?
You will be free!
How old are you?
代码展示:
age = input("How old are you?\n")
while age != 'quit':
numAge = int(age)
if numAge > 12:
print("You should pay 12 dollars!")
elif numAge >= 3:
print("You should pay 10 dollars!")
else:
print("You will be free!")
age = input("How old are you?\n")
7-8 熟食店
题目描述:
创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
INPUT:
None
OUTPUT:
I made you pork sandwich.
I made you chicken sandwich.
I made you tomato sandwich.
I made you tuna sandwich.
代码展示:
sandwich_orders = ['tuna', 'tomato', 'chicken', 'pork']
finished_sandwiches = []
while sandwich_orders:
finished_sandwiches.append(sandwich_orders.pop())
print("I made you " + finished_sandwiches[-1] + " sandwich.")