如果声明帮助Python

时间:2017-02-15 15:58:05

标签: python python-3.x

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错误" ?我环顾四周,如果条件错误,我觉得我是错的,但我不确定。

1 个答案:

答案 0 :(得分:0)

input方法以一种字符串形式返回用户输入,并尝试比较两种不同的类型(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类型,您可以以适当的方式处理它。