为什么这一部分的程序总是触发?

2024-04-20 06:04:15 发布

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

以下是我的节目节选:

weaponinput = input("Would you like a rifle, a pistol, or a shotgun?")
if weaponinput == " pistol":
    weapon = (int(pistol_1))
if weaponinput == " rifle":
    weapon = (int(rifle_1))
if weaponinput == " shotgun":
    weapon = (int(shotgun_1))
if weaponinput != (" shotgun") or (" rifle") or (" pistol") or (" sniper rifle"):
    print("In your futile attempt to turn",weaponinput,"into a weapon you accidentally blow your brains accross the ground.")

if子句总是在第8行触发,不管weaponinput的值是多少。为什么会这样?我用的是python,不太懂其他语言


Tags: oryouinputyourif节目likeint
3条回答

你写了相当于

if (w != 1) or (2) or (3):
 print("something")

(2)是非零的,因此为真。在代码中("rifle")不是None,因此是True。你知道吗

正确的形式是

if (w != 1) or (w!=2) or (w!=3):
    ...

另一种方法是

if weaponinput == "rifle:
    ...
elif weaponinput == "pistol": 
     ...
else:
    print("bad input message")

另一种方式:

WeaponCodes = {"pistol":int(pistol1), "rifle":int(rifle1), ... }
try:
   weapon = WeaponCodes[weaponinput]
except KeyError:
   print("bad input message")

Python会是:

if weaponinput not in (" shotgun", " rifle", " pistol", " sniper rifle"):
    print(...)

您需要将该行更改为以下内容:

if weaponinput != " shotgun" or weaponinput != " rifle" or weaponinput != " pistol" or weaponinput != " sniper rifle":

相关问题 更多 >