我正在编写一个拒绝访问未授权用户的安全系统.
import sys
print("Hello. Please enter your name:")
name = sys.stdin.readline().strip()
if name == "Kevin" or "Jon" or "Inbar":
print("Access granted.")
else:
print("Access denied.")
Run Code Online (Sandbox Code Playgroud)
它按预期授予对授权用户的访问权限,但它也允许未经授权的用户访问!
Hello. Please enter your name:
Bob
Access granted.
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我明确表示,只有在与nameKevin,Jon或Inbar相同时才授予访问权限.我也尝试过相反的逻辑if "Kevin" or "Jon" or "Inbar" == name,但结果是一样的.
我正在学习Python,而且我遇到了一些问题.在我正在考虑的课程中看到类似的东西后,想出了这个简短的剧本.我之前用过"或"用"if"成功(这里没有显示太多).出于某种原因,我似乎无法让这个工作:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey" or "monkeys":
print "You're right, they are awesome!!"
elif x != "monkey" or "monkeys":
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
Run Code Online (Sandbox Code Playgroud)
但是效果很好:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey":
print "You're right, they are awesome!!"
elif x != "monkey":
print …Run Code Online (Sandbox Code Playgroud)