输入错误时继续执行程序

时间:2019-06-04 02:16:34

标签: python

是python的新手,它试图创建一个输入pin号码的程序。

找到一个拒绝错误答案的循环,然后再次提出问题。问题是,这仅在用户输入数字时才有效,如果用户输入字符串或字符串和数字的组合,我会收到一条错误消息,而不是再次询问该问题。试图摆脱输入问题的int部分,但这只是导致我的程序无法识别正确的引脚。我正在使用python 3,如果有什么区别。

pin = {1111}  # Correct pin code

while True:
    enter_pin = int(input("Enter your pin: "))  # Ask user for pin code

    if enter_pin in pin:
        print("")
        print("Access granted")   # Grant access if correct pin entered
        break
    print("")
    print("Incorrect pin. Please try again")   # Repeat question and allow 
    another attempt if wrong pin is given
    print("")

下面的输出。与错误的数字,它的字符串是问题的正常工作。

Enter your pin: 42543653

Incorrect pin. Please try again

Enter your pin: 43623576325

Incorrect pin. Please try again

Enter your pin: v46tb563v3
Traceback (most recent call last):
  File "", line 4, in <module>
     enter_pin = int(input("Enter your pin: "))  # Ask user for pin code
 ValueError: invalid literal for int() with base 10: 'v46tb563v3'

Process finished with exit code 1

0 个答案:

没有答案