Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Input and Output

Read a password and hide it using getpass - Python Program

Example 1:

import getpass pwd = getpass.getpass("Enter password: ") print("Password accepted!")

Output

 
OUTPUT  :
Enter password:
Password accepted!
 

Example 2: Advanced Program

import getpass # Prompt the user for a password # The 'prompt' argument allows you to customize the message displayed to the user. password = getpass.getpass(prompt='Enter your password: ') # You can then use the 'password' variable for authentication or other purposes. # For demonstration purposes, we'll simply print a confirmation. print(f"Password entered is : {password}") # Example of a simple password check correct_password = "mysecretpassword" if password == correct_password: print("Login successful!") else: print("Incorrect password.")

Output

 
OUTPUT 1:
Enter your password: 
Password entered is : mysecretpassword
Login successful!


OUTPUT 2:
Enter your password: 
Password entered is : test
Incorrect password. 

Description

  • import getpass:

This line imports the getpass module, which contains the necessary functions for secure password input.

  • password = getpass.getpass(prompt='Enter your password: '):
    • getpass() is the core function used to prompt for input.
    • The promptargument is a string that will be displayed to the user before they enter their password. When the user types, the characters will not appear on the screen, providing a secure input mechanism.
    • The entered password (as a string) is stored in the password
  • print(f"Password entered : {password}"):

This line prints the entered password. In a real application, printing the password directly like this is highly discouraged for security reasons. It is included here only to demonstrate that the input was successfully captured.

  • correct_password = "mysecretpassword":

This defines a placeholder for a correct password for a simple comparison. In a real system, passwords should never be stored in plaintext; instead, they should be securely hashed and compared with hashed versions of the entered password.

  • if password == correct_password::

This if statement checks if the entered password matches the correct_password.

  • print("Login successful!")

and  print("Incorrect password."): These lines provide feedback to the user based on the password comparison.