首页 > 解决方案 > Python 3.6 elif 语法错误

问题描述

使用嵌套的 if 语句,我的缩进似乎是正确的,但仍然会出现语法错误。谢谢

# FIGHT Dragons
if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']:

    # WITH SWORD
    if sword == 1:
        print ("You only have a sword to fight with!")
        print ("You quickly jab the Dragon in it's chest and gain an advantage")
        time.sleep(2)
        print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        print ("                  Fighting...                   ")
        print ("   YOU MUST HIT ABOVE A 5 TO KILL THE DRAGON    ")
        print ("IF THE DRAGON HITS HIGHER THAN YOU, YOU WILL DIE")
        print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        time.sleep(2)
        fdmg1 = int(random.randint(3, 10))
        edmg1 = int(random.randint(1, 5))
        print ("you hit a", fdmg1)
        print ("the dragon hits a", edmg1)
        time.sleep(2)

        if edmg1 > fdmg1:
            print ("The drgon has dealt more damage than you!")
            complete = 0
        return complete 

这是我遇到语法错误的地方

        elif fdmg1 < 5:
            print ("You didn't do enough damage to kill the drgon, but you manage to escape")
            complete = 1
        return complete 
        else:
            print ("You killed the drgon!")
            complete = 1
        return complete 

标签: python-3.xsyntax

解决方案


您的回报必须在 if...elif...else 语句的末尾。这有效:

if edmg1 > fdmg1:
    print ("The drgon has dealt more damage than you!")
    complete = 0

elif fdmg1 < 5:
    print ("You didn't do enough damage to kill the drgon, but you manage to escape")
    complete = 1

else:
    print ("You killed the drgon!")
    complete = 1

return complete   

请注意,如果第一个 if 条件为 True,Python 将不会检查后续条件。


推荐阅读