-1

So I was messing around in Python. I couldn't think how to make it so that if you enter an invalid username/password, then it returns to the top of the loop and begins from the if statement again. When I enter an invalid username or password, it doesn't do this. So please could someone help me and explain why?

values = ["User1", "123", "User2", "321", "User3", "132"]

print("Please log in to the program")
username = input("Please enter your username: ")
attempts = 3
while attempts >=1:
    if username in values:
        place = values.index(username)
        passposition = int(place + 1)
        print("Your username is valid.")
        password = input("Now please enter the password to your account. Once again, passwords are case sensitive: ")
        if password == values[passposition]:
            print("The password is correct, welcome to the program")
        else:
            print("The password was invalid, please try again")
            attempts -= 1
            print("You now have ", attempts, " more attempts to log in with a valid username and password")
    else:
        print("Your username is invalid, please try again")

attempts -= 1 print("You now have ", attempts, " more attempts to log in with a valid username and password")

Emp5
  • 1
  • 1
    You're specifically looking for the `continue` statement, but you should also read [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Haugh Nov 07 '18 at 18:00

1 Answers1

0

Does this work for you?

values = ["User1", "123", "User2", "321", "User3", "132"]
attempts = 3
print("Please log in to the program")
while attempts >=1:
    #You need to ask for the username again, if you don't do this the variable is always assigned with a invalid value
    #That's why it must be inside the loop
    username = input("Please enter your username: ")
    if username in values:
        place = values.index(username)
        passposition = int(place + 1)
        print("Your username is valid.")
        password = input("Now please enter the password to your account. Once again, passwords are case sensitive: ")
        if password == values[passposition]:
            print("The password is correct, welcome to the program")
            #Once you have the right credentials you need to break the loop, if you comment the break you'll see that the programs asks again for the password
            break
        else:
            print("The password was invalid, please try again")
            attempts -= 1
            print("You now have ", attempts, " more attempts to log in with a valid username and password")
    else:
        print("Your username is invalid, please try again")
        attempts -= 1
        print("You now have ", attempts, " more attempts to log in with a valid username and password")
sirandy
  • 1,834
  • 5
  • 27
  • 32