首页 > 解决方案 > 在循环中为多个输入创建元音变量

问题描述

我正在尝试在循环中创建一个变量,如果该响应的第一个字母是元音,它将在响应中打印“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.

标签: pythonvariables

解决方案


问题是a_an每次下订单时都会覆盖变量。您需要为批量中的每个订单保存它。一种方法是在while循环中简单地将它与响应连接起来,

responses[name] = a_an + ' ' + response 

使用此修复程序,您的程序的其余部分保持不变,除了:

for name, response in responses.items():
    print(name + " would like " + response + " sandwich.")

推荐阅读