Python 初学者输入和不同的选择



虽然可能有更简单的方法可以做到这一点,但我希望了解出了什么问题。代码应该告诉你超级英雄的真实身份,当给出超级英雄的名字时。

问题是这样的:

在您提供超级英雄的真实姓名后,它会询问"您需要更多信息吗?您如何设置此问题的选择?

super_heros = {'Hulk': 'Bruce Banner',
               'Capitan America': 'Steve Rogers',
               'Spiderman': 'Peter Parker'}
hero_biography = {'Bruce Banner' : 'David Banner nasce in California...ecc'}
while True:
    choice = input('Nome Supereroe:') ###Superhero's name:
    if choice == 'Hulk':
        print(super_heros['Hulk'])
    elif choice == 'Bruce Banner':
        choice = input('Desideri maggiori informazioni?') ###Do you want more information
    elif choice == 'Yes': ### I know that this one will refer to : choice = input('Nome Supereroe:')
        print(hero_biography['Bruce Banner'])
    elif choice == 'Capitan America':
        print(super_heros['Capitan America'])
    elif choice == 'Spiderman':
        print(super_heros['Spiderman'])
    elif choice == 'Esc':
        break
    else:
        choice == ''
        print('Nome inesistente')

将嵌套条件与另一个变量一起使用,例如 choice2

...
elif choice == 'Bruce Banner':
    choice2 = input('Desideri maggiori informazioni?')
    if choice2 == "Yes":
        print(hero_biography['Bruce Banner'])
elif choice == 'Captain America':
...

问题是你使用"elif"而不是嵌套的"if"来检查,如果第二个选择是"是"。

如果将代码拆分为较小的块(函数),这将很有帮助。然后你可以像这样编写代码:

choice = input('Nome Supereroe:')
while choice != 'Esc':
    printCharacterInfo(choice)
    choice = input('Nome Supereroe:')
def printCharacterInfo(character):
    try:
        print(super_heros[character])
    except KeyError:
        if character in hero_biography:
            proposeBiographyInformation(character)
        else:
            print('Nome inesistente')
def proposeBiographyInformation(name):
    if input('Desideri maggiori informazioni?') == 'Yes':
        print(hero_biography[name])

如果满足任何 elif 条件,则不会检查下一个 elif 条件。
如果您的输入:诺姆超级:布鲁斯班纳它满足 elif 选择 == "布鲁斯班纳":条件和您在此处的输入是Desideri maggiori informazioni?是的
我不会检查 elif 选择 == "是":条件,因为它已经满足您之前的条件。

如果再次使用输入函数并分配给不同的变量,则不会影响原始输入。 您可以在块结束的地方要求这样做,即在其他地方。 例如。。

...
else:
        choice == ''
        print('Nome inesistente')
newChoice = input('Do you need more information?')
#your code to handle new choice user entered.
我会

这样尝试:

while True:
    choice = input('Nome Supereroe:')
    if choise in super_heros:
        print(super_heros[choise])
    elif choise in hero_biography:
        moreInformation = input('Desideri maggiori informazioni?')
        if moreInformation == 'yes':
            print(hero_biography[choise])
    else:
        print('Nome inesistente')

最新更新