python在继续之前等待第n位数

时间:2017-12-18 09:02:31

标签: python python-2.7

from pad4pi import rpi_gpio

# Setup Keypad
KEYPAD = [
        ["1","2","3","A"],
        ["4","5","6","B"],
        ["7","8","9","C"],
        ["*","0","#","D"]
]

ROW_PINS = [5,6,13,19] # BCM numbering
COL_PINS = [26,16,20,21] # BCM numbering

factory = rpi_gpio.KeypadFactory()

keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)

def processKey(key):
 print("enter 3 digit")
 print(key)
 if key == 123:
  print("correct")
 else:
  print("wrong password")

keypad.registerKeyPressHandler(processKey)

我希望代码等待用户输入例如3位数字,然后再与上面代码中的123代码中的密码进行比较。

它应该做什么:

等待用户从键盘输入3位数字,例如123,然后打印正确。

它实际上做了什么:

用户输入1位数代码后,它会立即打印正确或错误的密码

2 个答案:

答案 0 :(得分:1)

更新覆盆子服用@furas示例:

# Initial keypad setup
code = ''

def processKey(key):
    print("Enter your 3 digit PWD: \n")
    global code
    MAX_ALLOWED_CHAR = 3
    code += key
    if (len(code) == MAX_ALLOWED_CHAR):
        if (code == "123"): 
            print("You entered the correct code.")
            dostuff()
        else:
            code = ''        
            print("The passcode you entered is wrong, retry.")

def dostuff():
    # do your things here since passcode is correct.

这可能适合你的情况。

def processKey():

    key = input("enter 3 digit")
    if (key == "123"):
        print("Correct password.")
        return True
    else:
        print("You typed {0} wich is incorrect.".format(key))
        return False

所以现在你不给processKey一个值因为你说用户输入它,调用processKey()会要求用户输入密码并根据" 123&#返回true / false 34;在检查中。

如果你想输入密码,但如果以下答案不符合你的需要(没有完全理解你想要完成的事情),那就提供更聪明的例子。

编辑:

由于您想要严格输入3位数字并重新输入密码,以防他们输入错误的密码,您可以执行以下操作:

在调用processKey()时,你可以:

while (processKey() == False):
    processKey()

修改后的代码符合您的需求:

def processKey():
    MAX_ALLOWED_CHAR = 3
    key = input("Enter 3 digit PWD: \n")
    if (key == 123):
        print("Correct password.")
        return True
    elif (len(str(key)) > MAX_ALLOWED_CHAR):
        print("The max allowed character is {0}, instead you entered {1}.".format(MAX_ALLOWED_CHAR,key))
        return False
    else:
        print("You typed {0} wich is incorrect.".format(key))
        return False

while (processKey() == False):
    processKey()

输出:

Enter 3 digit PWD: 
3333
The max allowed character is 3, instead you entered 3333.
Enter 3 digit PWD: 
321
You typed 321 wich is incorrect.
Enter 3 digit PWD: 
123
Correct password.

答案 1 :(得分:1)

每次按键后都会执行

按键 - 这很自然。您必须将所有密钥保留在列表或字符串中并检查其长度。

code = ''

def processKey(key):
    global code

    code += key

    if len(code) == 3:
        if code == "123": 
           print("correct")
        else:
           print("wrong password, try again")
           code = ''