python在继续之前等待第n位数
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代码中的密码进行比较。python在继续之前等待第n位数
它应该做的:
等待用户从键盘输入3位,例如123,然后打印正确。
什么它实际上做:
它将打印正确或不正确的密码后,用户马上进入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“在检查。
这是如果你想输入密码,但如果下面的答案不适合你的需求(没有完全理解你想完成的)只是提供更聪明的例子。
编辑:
既然你想严格有3位输入的情况下,重新输入密码,他们输入了错误的一个,你可以做到以下几点:
在调用processKey()您可以:
while (processKey() == False): processKey()
Revisioned代码来满足您的需求:
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.
回答:
按键每按一次键执行 - 这是自然的。你必须把所有的钥匙放在列表或字符串中,并检查它的长度。
code = '' def processKey(key):
global code
code += key
if len(code) == 3:
if code == "123":
print("correct")
else:
print("wrong password, try again")
code = ''
以上是 python在继续之前等待第n位数 的全部内容, 来源链接: utcz.com/qa/261915.html