怎样才能让我的循环在计时器后重新开始?

2024-09-29 02:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使此代码再次启动while循环,直到用户输入正确的密码

userPassword =input('parola;')
userPasswordId = input('parola')
counter = 0
while userPasswordId != userPassword and counter < 3:
    print('Sorry the password is incorect.Try again!')
    counter = counter + 1
    print('You have', 3 - counter, 'attempts left.')
 userPasswordId = input('Enter your password:')
if counter == 3:
    print('Your account is locked for 30 seconds!!!!!')
    import time
    sec = 0
    while sec != 5:
        print('>>>>>>>>>>>>>>>>>>>>>', sec)
    # Sleep for a sec
        time.sleep(1)
    # Increment the minute total
        sec += 1

Tags: the代码用户forinputtimeiscounter
2条回答

这叫做异步编程。Python中引入了async和await关键字

import asyncio 
async def allowInput():
    await asyncio.sleep(30000) #ms
    # your code goes here

只需将if counter == 3行及其下的块移到while循环中

为了改进用户看到的消息流,我也对代码进行了一些重构

举个例子:

import time


userPassword =input('parola;')
counter = 0

while True:
    userPasswordId = input('Enter your password:')
    if userPasswordId != userPassword:
        print('Sorry the password is incorect.Try again!')
        counter += 1
        print('You have', 3 - counter, 'attempts left.')
    else:
        break

    if counter == 3:
        counter = 0
        print('Your account is locked for 30 seconds!!!!!')
        sec = 0
        while sec != 5:
            print('>>>>>>>>>>>>>>>>>>>>>', sec)
        # Sleep for a sec
            time.sleep(1)
        # Increment the minute total
            sec += 1

此代码将继续循环,直到用户输入正确的密码,此时它将break执行循环

相关问题 更多 >