Username and password inputs with 3 attempts in Python

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Username and password inputs with 3 attempts in Python #

To take username and password input values with 3 attempts:

  1. Use a while loop to iterate a maximum of 3 times.
  2. Use the input() function to take values for the username and password from the user.
  3. If the credentials are correct, break out of the loop.
main.py
attemps = 0 while attemps < 3: username = input('Enter your username: ') password = input('Enter your password: ') if username == 'user123' and password == 'password123': print('You have successfully logged in.') break else: print('Incorrect credentials. Check if you have Caps lock on and try again.') attemps += 1 continue

username password input 3 attempts

We used a while loop to iterate a maximum of 3 times.

On each iteration, we prompt the user for a username and a password and check if the values are correct.

If you want to hide the password text while the user is typing, use the getpass() method.

main.py
import getpass attemps = 0 while attemps < 3: username = input('Enter your username: ') password = getpass.getpass('Enter your password: ') if username == 'user123' and password == 'password123': print('You have successfully logged in.') break else: print('Incorrect credentials. Check if you have Caps lock on and try again.') attemps += 1 continue

username password input 3 attemps password hidden

We used the getpass() method from the getpass module to prompt the user for a password without echoing.

The getpass module is available in the standard library, so you don't have to install anything.

The getpass method is usually used to prompt the user for a password or other sensitive information.

If both conditions in the if statement evaluate to True, the if block runs where we break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

If one or both conditions evaluate to False, the else block runs.

In the else block, we increment the attempts variable by 1 and continue to the next iteration of the while loop.

The continue statement continues with the next iteration of the loop.

If the user enters incorrect credentials 3 times, the attempts variable gets set to 3 and the condition in the while loop is no longer met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.