7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是10的整数倍。
num = int(input('Please input a number: '))
if num % 10 == 0:
print("It's divisible by 10.")
else:
print("It's not divisible by 10.")
输入:
20
输出:
Please input a number: 20
It's divisible by 10.
7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入’quit’ 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
prompt = "Please enter the ingredient you want to add to your pizza:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
ingredient = input(prompt)
if ingredient == 'quit':
break
else:
print('We will add ' + ingredient + ' to your pizza.\n')
输入:
mushrooms
green peppers
extra cheese
quit
输出:
Please enter the ingredient you want to add to your pizza:
(Enter 'quit' when you are finished.) mushrooms
We will add mushrooms to your pizza.
Please enter the ingredient you want to add to your pizza:
(Enter 'quit' when you are finished.) green peppers
We will add green peppers to your pizza.
Please enter the ingredient you want to add to your pizza:
(Enter 'quit' when you are finished.) extra cheese
We will add extra cheese to your pizza.
Please enter the ingredient you want to add to your pizza:
(Enter 'quit' when you are finished.) quit
7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
responses = {}
prompt = 'If you could visit one place in the world, where would you go? '
active = True
while active:
name = input('What is your name? ')
response = input(prompt)
responses[name] = response
repeat = input('Would you like to let another person respond? (yes/ no) ')
if repeat == 'no':
active = False
else:
print()
print('\n--- Poll Results ---')
for name, response in responses.items():
print(name.title() + ' would like to visit ' + response.title() + '.')
输入:
alice
london
yes
bob
new york
yes
trump
China
no
输出:
What is your name? alice
If you could visit one place in the world, where would you go? london
Would you like to let another person respond? (yes/ no) yes
What is your name? bob
If you could visit one place in the world, where would you go? new york
Would you like to let another person respond? (yes/ no) yes
What is your name? trump
If you could visit one place in the world, where would you go? China
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Alice would like to visit London.
Bob would like to visit New York.
Trump would like to visit China.