[英]Why does this piece of my program always trigger?
这是我程序的摘录:
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
输入的值weaponinput
。 为什么会这样? 我正在使用python,但并不真正了解许多其他语言
您写了相当于
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")
您需要将该行更改为以下内容:
if weaponinput != " shotgun" or weaponinput != " rifle" or weaponinput != " pistol" or weaponinput != " sniper rifle":
Pythonic将是:
if weaponinput not in (" shotgun", " rifle", " pistol", " sniper rifle"):
print(...)
要检查多个条件,您必须将输入变量与所需条件进行比较,例如:
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":
出所有运营商,逻辑运算符( or
, and
和not
)具有最低优先级( Python的运算符优先级 )。
在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.")
因此,在第8行的条件始终是否属实,不论weaponinput
等于" shotgun
”或没有(如or
结果始终为true,如果它的操作数的ATLEAST一个是真实的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.