If 语句和 else 没有按预期工作[关闭]

Posted

技术标签:

【中文标题】If 语句和 else 没有按预期工作[关闭]【英文标题】:If statements & else not working as intended [closed] 【发布时间】:2020-07-26 19:35:14 【问题描述】:
    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()

它总是让我心脏病发作。

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

【问题讨论】:

你需要elif 如果您是初学者,那么在这种情况下阅读一些有关 Python 的基础教程可能是一个很好的主意。您似乎遇到的问题应该被他们和许多其他有用的东西所涵盖。 【参考方案1】:

最好每次只使用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()

【讨论】:

【参考方案2】:

也许这个解决方案就足够了。

试试elif statements。

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")
    exit()

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()

【讨论】:

以上是关于If 语句和 else 没有按预期工作[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

解决了| Python:If/elif/else 语句未按预期工作?

因为某些原因。 IF 语句正在工作....我试过 If/else 也没有运气[关闭]

嵌套的 if else 语句无法通过目标单元格工作

如何在 JavaScript 中编写没有“else”的 IF else 语句 [关闭]

简化javascript中的嵌套if else语句[关闭]

优化if -else语句问[关闭]