How can I fix this Python login system code?

时间:2019-04-08 13:41:26

标签: python python-3.x

I am trying to make a login system in Python, so that I have to put a specific username and password to login.

This is the code:

    uname = input("Enter username: ")
    username = "John"
    password = "John123"
    attempts = 0

    while attempts != 3:
        if uname == username:
            pword = input("Enter password: ")
        else:
            print("Invalid Username...")
        if pword == password:
            print("Login successful!")
            break
        else:
            attempts += 1

    if attempts == 1:
        print("You have 2 attempts left")
    elif attempts == 2:
        print("You have 1 attempt left")

    if attempts == 3:
        print("Validation failed...")

My expected result is when I enter a wrong username, it lets me enter a username again after printing "Invalid Username..." and if I enter the right username, it lets me enter the password However, the output is:

Invalid Username... Traceback (most recent call last): File "/Users/(username)/Desktop/loginsystem.py", line 11, in module> if pword == password: NameError: name 'pword' is not defined

I have already tried adding a "continue" statement, but keeps on looping "Invalid Username..." infinitely.

It works fine when I enter the right username though.

2 个答案:

答案 0 :(得分:0)

If you move the password check to the inside of the if you can make the code a bit more straight foward.

while attempts != 3:
        uname = input('Enter username: ')
        if uname == username:
            pword = input("Enter password: ")
            if pword == password:
                print("Login successful!")
                break
            else:
               print('Invalid Password')
        else:
            print("Invalid Username...")

        attempts += 1

答案 1 :(得分:0)

Move the user input inside the loop, and implement a decrement check for attempts:

username = "John"
password = "John123"
attempts = 3

while attempts > 0:
    uname = input("Enter username: ")
    attempts -= 1
    if uname == username:
        pword = input("Enter password: ")
    else:
        print("Invalid Username...")
        print("You have {} attempts left.".format(attempts))
        continue
    if pword == password:
        print("Login successful!")
        break
    else:
        print("Invalid Password...")
        print("You have {} attempts left.".format(attempts))

OUTPUT:

Enter username: Mike
Invalid Username...
You have 2 attempts left.
Enter username: John
Enter password: mike123
Invalid Password...
You have 1 attempts left.
Enter username: John
Enter password: John123
Login successful!

EDIT:

I'd suggest using a while True and a break statement inside, something like:

while True:
    uname = input("Enter username: ")
    attempts -= 1
    if attempts <= 0:
       break
    if uname == username:
        # rest of the code
相关问题