【问题标题】:Looping User Input For Multiple Inputs Without Running Multiple Times为多个输入循环用户输入而不运行多次
【发布时间】:2020-02-03 23:20:23
【问题描述】:

有没有办法在 python 3.8 中将输入放入循环中?

我想多次获得用户输入,而不必多次运行程序。

我想输入一个英雄并得到一个答案,然后能够输入另一个英雄而不用一遍又一遍地运行。

如果有人有任何建议,请告诉我。

谢谢!

"""

This program is intended to compare heroes from Marvel and DC. Enter 
your 
hero choice and see what hero from #Marvel or DC is most like them.
I know there are simpler ways to write this code so if anyone has any 
suggestions please leave them for me
Thanks for viewing!

Only the heroes below can be entered

marvel = ['Moon Knight', 'Hyperion', 'Thor', 'Punisher', 'Jean Grey', 
'Iron Man', 'Quicksilver']

DC = ['Batman', 'Superman', 'Shazam', 'Red Hood', 'Wonder Woman', 
'Batwing', 'Flash']
"""

choice = str(input('Choose a hero\n'))


def hero_choose():
    if choice.lower() == 'batman':
        return('Moon Knight')
    if choice.lower() == 'moon knight':
        return('Batman')
    if choice.lower() == 'superman':
        return('Hyperion')
    if choice.lower() =='hyperion':
        return('Superman')
    if choice.lower() == 'thor':
        return('Shazam')
    if choice.lower() == 'shazam':
        return('Thor')
    if choice.lower() == 'red hood':
        return('punisher')
    if choice.lower() == 'punisher':
        return('Red Hood')
    if choice.lower() == 'wonder woman':
        return('Jean Grey')
    if choice.lower() == 'jean grey':
        return('Wonder Woman')
    if choice.lower() == 'iron man':
        return('Batwing')
    if choice.lower() == 'batwing':
        return('Iron Man')
    if choice.lower() == 'flash':
        return('Quicksilver')
    if choice.lower() == 'quicksilver':
        return('Flash')
    else:
        return('Your hero may not be available\nor your spelling may be 
wrong.')

print(hero_choose())

【问题讨论】:

    标签: python-3.x loops input


    【解决方案1】:

    您是否考虑过让您的用户输入一个以逗号分隔的值列表?比如

    $ python choose_hero.py
    Please enter hero names seperated by a "," (e.g. batman,robin)
    Names: batman,superman
    Moon Night
    Hyperion
    

    如下实现

    print("Please enter hero names seperated by a \",\" (e.g. batman,robin)")
    choices = [name for name in str(input('Names: ')).split(',')]
    for choice in choices:
      # your implementation of hero_choose will need to be modified 
      # to accept a param, rather than using the global choice var
      hero_choose(choice)
    

    我知道这不是代码审查堆栈,但如果我能提出与您的问题无关的建议。考虑使用Dictionary as a switch statement 而不是无穷无尽的 if 语句

    【讨论】:

    • 是的,我考虑过使用字典,但对 python 来说还很陌生,我不太确定如何使用它。我会尝试你的第一个建议,看看它是如何工作的。谢谢。
    • @CodyGreathouse 附加的链接应该会给你一些关于使用字典的指导。希望能解决您的问题!如果是这样,请务必将问题标记为已回答
    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2016-09-18
    • 2015-04-20
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多