Prompt for username and password in Python

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Prompt for username and password in Python #

To prompt the user for username and password:

  1. Use the input() function to take non-sensitive input values, such as the username.
  2. Use the getpass() method to take sensitive values, such as the password.
main.py
import getpass # ✅ Prompt for username and password username = input('Enter your username: ') print(username) password = input('Enter your password: ') print(password) # ---------------------------------------------------- # ✅ Prompt for username and password with hidden inputs username = getpass.getpass('Enter your username: ') print(username) password = getpass.getpass('Enter your password: ') print(password)

The first example uses the input() function to take the user's username and password.

The input() function shows the text as the user is typing.

user input username and password

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

Note that the input() function is guaranteed to return a string even if the user enters a number.

The second example uses the getpass method to take the user's username and password without showing the text as the user is typing.

main.py
import getpass username = getpass.getpass('Enter your username: ') print(username) password = getpass.getpass('Enter your password: ') print(password)

input username and password hidden

We used the getpass() method from the getpass module to prompt the user for input 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.

The argument the method takes is the message that is displayed to the user.

You can also combine the solutions and use the input() function to take the username and the getpass() method to take the password.

main.py
import getpass username = input('Enter your username: ') print(username) password = getpass.getpass('Enter your password: ') print(password)

input username shown password hidden

The input() function prompts for the username and shows the text while the user is typing.

The getpass() method prompts for the user's password and hides the text.

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.