Python:键盘输入和循环
我想用覆盆子皮做一个储物柜。我有一个代码,当用USB键盘输入正确的代码='1234'时,它会打开一个伺服。 基本上它是工作的,但需要以某种方式循环,所以,如果我输入了错误的PIN,我会再次被要求输入正确的PINPython:键盘输入和循环,python,loops,raspberry-pi,Python,Loops,Raspberry Pi,我想用覆盆子皮做一个储物柜。我有一个代码,当用USB键盘输入正确的代码='1234'时,它会打开一个伺服。 基本上它是工作的,但需要以某种方式循环,所以,如果我输入了错误的PIN,我会再次被要求输入正确的PIN for event in dev.read_loop(): if event.type == ecodes.EV_KEY: e = categorize(event) if e.keystate == e.key_down:
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
e = categorize(event)
if e.keystate == e.key_down:
klawisz = e.keycode[4:]
if klawisz != "ESC":
kod = (kod + klawisz)
print(kod)
else:
break
if kod == '1234':
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
d = categorize(event)
if d.keystate == d.key_down:
klawisz = d.keycode[4:]
if klawisz == "ESC":
print('ITS OPEN')
break
else:
break
else:
print('Wrong PIN')
我在开始时尝试了while循环,但它不起作用:(
希望您能指导我找到正确的解决方案,因为我仍在学习Python。谢谢。使用无限
while
循环,仅当代码匹配时才中断循环
while True:
code = input('Enter code: ')
if code == '1234':
print('Code accepted.')
break
print('Wrong code, try again.')
您可以轻松添加额外的安全功能,以减少每次尝试的次数
import time
attempts = 0
while True:
code = input('Enter code: ')
if code == '1234':
print('Code accepted.')
break
print('Wrong code, try again.')
attempts = attempts + 1
if attempts > 9:
print('Too many failed attempts. Please wait.')
time.sleep(600)
attempts = 0
您可以在普通计算机上运行上面的所有示例来测试它们。它们使用Python内置的
输入
函数。您可以使用返回键来完成输入,而不是代码中的ESC键。您说过您使用USB键盘读取用户输入,因此输入
甚至可能也适用于您的Raspberry Pi如果某些条件保持为真,则可以使用while循环重复执行某些操作(在示例中读取用户密码):
def read_password():
kod = ""
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
e = categorize(event)
if e.keystate == e.key_down:
klawisz = e.keycode[4:]
if klawisz != "ESC":
kod = (kod + klawisz)
print(kod)
else:
break
return kod
while read_password() != '1234':
print('Wrong PIN, try again')
在这种情况下,只要密码与“1234”不匹配,您就可以读取密码。请编辑您的问题标题,使其更有意义。此外,您应该尝试抽象代码(您的算法)进一步。例如,将关于从用户输入中读取密码的部分放入函数中。这将帮助您创建一个更短的部分,这将导致更清晰的问题,并且您将在a)自己寻找解决方案时获得更好的搜索结果,b)在这里获得更好更快的答案。谢谢,这就是我一直在寻找的。工作起来很有魅力。
def read_password():
kod = ""
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
e = categorize(event)
if e.keystate == e.key_down:
klawisz = e.keycode[4:]
if klawisz != "ESC":
kod = (kod + klawisz)
print(kod)
else:
break
return kod
while read_password() != '1234':
print('Wrong PIN, try again')