首页 > 解决方案 > if 语句 & else 没有按预期工作

问题描述

    if b1a == "rock":
    print("you gave him a concussion and made the rock your new weapon")
    weapon = "rock"
else:
    print("you had a heart attack because you didn't pick one of the options")
    exit()

if b1a == "NIGERUNDAYO":
    weapon = "tommy gun"
    print("You ran so much that the beast got tired, then you took out a tommy gun and started shooting")
else:
    print("you had a heart attack because you didn't pick one of the options")
    exit()

if b1a == "slash":
    print("you slashed his face with a hatchet. ")
else:
    print("you had a heart attack because you didn't pick one of the options")
    exit()

它总是让我心脏病发作。

我是初学者,想知道是否有其他方法可以解决这个问题。

标签: pythonpython-3.x

解决方案


最好elif每次只使用而不是if-else构造。

if b1a == "rock":
    print("you gave him a concussion and made the rock your new weapon")
    weapon = "rock"
elif b1a == "NIGERUNDAYO":
    weapon = "tommy gun"
    print("You ran so much that the beast got tired, then you took out a tommy gun and started shooting") 
elif b1a == "slash":
    print("you slashed his face with a hatchet. ")
else:
    print("you had a heart attack because you didn't pick one of the options")
    exit()

推荐阅读