社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

尝试对用户输入使用词典(python)

Cody Greathouse • 5 年前 • 1432 次点击  

有人能帮我吗?我正在想办法简化这段代码。人们一直建议用字典,但我不知道怎么用。我只想缩短代码的长度,而不是使用那么多if语句。同样为了澄清,我想让用户输入一个英雄,并有一个不同的英雄打印回来。

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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54272
 
1432 次点击  
文章 [ 2 ]  |  最新文章 5 年前