我将如何添加一个while循环和计数器,管理员可以使用该代码登录

时间:2017-10-31 19:45:41

标签: python python-3.x loops while-loop counter

def login():
    logindetails = {'username':'Admin123' , 'password':'Pass123'}

    username = input("please enter the username")
    password = input("please enter the password")

    if username == 'Admin123':
        print ("username correct")
    else:
        print ("username incorrect")
    if password == 'Pass123':
        print ("password correct")
    else:
        print ("password incorrect")

login()

请告诉我在哪里放置while循环以及如何格式化代码以添加计数器。

2 个答案:

答案 0 :(得分:0)

首先,您应该将用户名和密码变量初始化为空字符串以及计数器。

然后,你应该用for condition声明你的while循环,

之间的比较
  • 用户名和logindetails ['用户名']
  • 密码和logindetails ['密码']。

如果两者相同,你就会越过循环,如果没有,你必须再次询问用户输入并增加计数器。

换句话说:

username = ""
password = ""
counter = 0

WHILE username != logindetails['username'] AND password != logindetails['password']:
    ASK for user inputs / DISPLAY error messages
    INCREMENT counter

DISPLAY "logged after counter attempts"

它能回答你的问题吗?

答案 1 :(得分:0)

您可以这样做:

def login():
    logindetails = {'username':'Admin123' , 'password':'Pass123'}

    username = input("please enter the username")
    password = input("please enter the password")
    valid = False
    while valid == False:
        if username == 'Admin123' and password == 'Pass123':
            print ("username and password correct")
            valid = True
            pass
        else:
            print ("username or password incorrect")
        username = input("please enter the username")
        password = input("please enter the password")

有效是bool所以循环不会停止,直到用户名和密码正确。

或者你可以有一个故障保险,如果用户输入的用户名和密码错误超过4次,就会把它们踢掉。

def login():
    logindetails = {'username':'Admin123' , 'password':'Pass123'}

    username = input("please enter the username")
    password = input("please enter the password")
    valid = False
    count = 0
    while count != 4 or valid == False:
        if username == 'Admin123' and password == 'Pass123':
            print ("username and password correct")
            valid == True
            pass
        else:
            print ("username or password incorrect")
            count += 1
        username = input("please enter the username")
        password = input("please enter the password")
    if valid == False:
        print ("Sorry you had too many attempts to login. Try again later")