具有多个if语句的条件语句(涉及原始输入)

2024-05-16 05:43:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试验原始输入,除了我的第一条if语句和else语句外,它运行得很好。每当我运行代码并用第一条if语句中“League”后面列出的原始输入回答第二个问题时,它将同时返回第一个if的打印和else的打印,而它应该只打印第一个if。你知道怎么回事吗?在

name = raw_input('What is your name?\n')
game = raw_input('\nWhat MOBA do you play/have played? \n(The answer ' \
    'must be case sensitive i.e. LoL for League and DoTA for y\'know the whole darn thing '\
    'is too '\
    'darn long to say even though I typed a lot more than the name)\n')

if game in ('League' , 'League of Legends' , 'LoL'):
    print '\nYou go girl! '
if game in ('DoTA' , 'DoTA 2' , 'DoTA2'):
    print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
    print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s.  You ' \
        'should at least be playing ' \
        'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)

Tags: nameinyougameinputplayrawif
3条回答

您可以始终将if用于第一个条件,使用elif表示任意数量的其他条件(如果输入在实例中的第二个列表中),并且{}如果输入不在这些列表中的任何一个列表中,则缩进也会有点混乱,相互嵌套的if语句只会在第一个条件的情况下运行嵌套的条件语句是真的,我还建议您对用户输入使用string.lower()方法,这样就不必指示用户键入区分大小写的输入并使用变量来存储这些列表,这样您就可以在代码的其他地方重用它们了

name = raw_input('What is your name?\n')
game = (raw_input('\nWhat MOBA do you play/have played?')).lower()

awesomeGames=['league' , 'league of legends' , 'lol']
coolGames=['dota' , 'dota 2' , 'dota2']
if game in awesomeGames:
    print '\nYou go girl! '
elif game in coolGames:
    print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
    print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s.  You ' \
    'should at least be playing ' \
    'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)

缩进级别不正确。 为第二个if语句再花一个空格。 或者少1个空格和elif而不是第二个if。在

将第二个if条件替换为elifelif可以任意多次使用,直到条件匹配为止,但最好的做法是将最后一个条件设为else(这与其他条件失败时的默认语句类似)

相关问题 更多 >