python - 在循环中为多个输入创建元音变量
问题描述
我正在尝试在循环中创建一个变量,如果该响应的第一个字母是元音,它将在响应中打印“an”。这是我的脚本:
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which kind of sandwich do you want? ")
if response[0] in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
a_an = "an"
else:
a_an = "a"
responses[name] = response
repeat = input("Would you like to let another person order? (yes/no) ")
if repeat == 'no':
polling_active = False
print("\n-- Order --")
for name, response in responses.items():
print(name + " would like " + a_an + " " + response + " sandwich.")
这是输出。当只接受一个订单时,变量有效,但当接受多个订单时,a_an
变量保持不变。
Python ❯ python3 sandwich_orders.py ⏎
What is your name? Alex
Which kind of sandwich do you want? egg
Would you like to let another person order? (yes/no) no
-- Order --
Alex would like an egg sandwich.
Python ❯ python3 sandwich_orders.py
What is your name? Alex
Which kind of sandwich do you want? ham
Would you like to let another person order? (yes/no) no
-- Order --
Alex would like a ham sandwich.
Python ❯ python3 sandwich_orders.py
What is your name? Alex
Which kind of sandwich do you want? egg
Would you like to let another person order? (yes/no) yes
What is your name? Steve
Which kind of sandwich do you want? ham
Would you like to let another person order? (yes/no) no
-- Order --
Alex would like a egg sandwich.
Steve would like a ham sandwich.
解决方案
问题是a_an
每次下订单时都会覆盖变量。您需要为批量中的每个订单保存它。一种方法是在while循环中简单地将它与响应连接起来,
responses[name] = a_an + ' ' + response
使用此修复程序,您的程序的其余部分保持不变,除了:
for name, response in responses.items():
print(name + " would like " + response + " sandwich.")
推荐阅读
- php - 仅当类别具有产品 WooCommerce 时才在 foreach 中返回结果
- reactjs - 第一个按钮单击后反应组件不更新
- c# - 图片不是从某些网站加载的
- swagger - .Net核心应用程序中的配置方法面临问题
- javascript - 使用二叉树的迭代解决方案来获得等于目标总和的路径总和时遇到问题
- jquery - 如何使用 jQuery 从多个集合选择中提取 id?
- mongodb - 如何仅允许用户访问 docker 中的 MongoDB?
- java - 为什么在heroku上部署时找不到jarfile?
- ios - SwiftUI ViewModel 发布的属性和绑定
- java - add (List ) 其中 Z 是一个 interface 。B 类扩展 A 实现 Z 为什么我们不能用 List 调用 add()