如果语句帮助Python

如果语句帮助Python

问题描述:

keyCounter = 0 
key1Value = 0 
key2Value = 0 
key3Value = 0 

print(key1Value) 

key1Value = input("Press the first key.") 
key2Value = input("Press the second key.") 
key3Value = input("Press the third key.") 
# password = 123 

if key1Value == 1 and key2Value == 2 and key3Value == 3: 
    print("Access Granted") 
    print(key1Value) 
    print(key2Value) 
    print(key3Value) 
elif key1Value != 1 and \ 
     key2Value != 2 and \ 
     key3Value != 3: 
     print("Access Denied") 
     print(key1Value) 
     print(key2Value) 
     print(key3Value) 
else: 
    print("Vault error") 
    print(key1Value) 
    print(key2Value) 
    print(key3Value) 

input("Press Enter to continue...") 

为什么总是导致“Vault Error”?我环顾四周,我觉得如果条件不对,但我不确定。如果语句帮助Python

+0

因为'input'总是返回一个字符串。换句话说,你试图比较'1'和''1''。使用'int(input(“按第一个键。”))'。 – roganjosh

+3

如果你输入一个类似'126'的代码(其中两个值匹配,但一个不匹配),你会得到一个“Vault Error”而不是“Access Denied”。如果*号码不匹配,您只会看到“访问被拒绝”。我不确定这是否是您正在寻找的结果。这可能不是问题,但我只想指出:'key1Value == 1和key2Value == 2和key3Value == 3'的倒数实际上是'key1Value!= 1或key2Value!= 2或key3Value != 3'(这是由于[德摩根法律](https://en.wikipedia.org/wiki/De_Morgan%27s_laws))。 –

输入方法返回用户输入的字符串类型,并尝试比较两个类型不同(int和STR)

变化的比较为str,例如:

if key1Value == "1" and key2Value == "2" and key3Value == "3": 

您也可以施放输入转换成int:

key1Value = int(input("Press the first key.")) 

通知时,你会不会插入实际数量,你会得到一个错误。

总之,我会做到以下几点:

try: 
    value=int(input("Press the first key.")) 
except ValueError: 
    print("This is not a whole number.") 

这样,您就可以检查用户输入是否为int的类型,如果它不是一个int类型,你可以在处理它适当的方式。

+0

这很有道理。谢谢! – Veinq