为什么我的程序总是会触发?

时间:2017-05-08 20:26:13

标签: python if-statement

以下是我的节目的摘录:

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,并没有真正理解许多其他语言

5 个答案:

答案 0 :(得分:4)

您已写过相当于

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

(2)非零,因此为True。在您的代码中("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")

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

Pythonic将是:

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

答案 3 :(得分:0)

要检查多个条件,您必须将输入变量与所需条件进行比较,如:

if var <conditional operator1> condition1 <logical operator> var <conditional operator2> condition2等等。

所以在你的情况下,第8行必须是: if weaponinput != " shotgun" or weaponinput != " rifle" or weaponinput != " pistol" or weaponinput != " sniper rifle":

答案 4 :(得分:0)

在所有运算符中,逻辑运算符(orandnot)的优先级最低(Python Operator Precedence)。

在Python中,非空字符串的布尔值始终为true。

因此,您编写的代码相当于: -

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 True or True or True:
    print("In your futile attempt to turn",weaponinput,"into a weapon you accidentally blow your brains accross the ground.")

因此,无论weaponinput是否等于" shotgun“,第8行中的条件始终为真(因为or如果其操作数的至少一个是dos2unix <file> ,则总是求值为真是的。