Quizzma Latest Questions

Write a Python program that prompts a user for a password using a loop

Anonymous

Write a Python program that prompts a user for a password using a loop. The program should repeatedly ask the user to enter the correct password, comparing it to a predefined secret password (SECRET set to abc123). If the user enters the correct password, the program should print “You got it!” and exit the loop. If the user enters the wrong password, the program should print an error message and prompt the user to try again.

Requirements:

  • Use a loop to repeatedly ask for the password.
  • Print an error message if the input does not match the secret password.
  • Exit the loop and print “You got it!” when the correct password is entered.

Sample Output:

Enter password: 123123
Sorry, that did not match. Please try again.
Enter password: password
Sorry, that did not match. Please try again.
Enter password: CODEHS
Sorry, that did not match. Please try again.
Enter password: abc123
You got it!




Leave an answer

Leave an answer

2 Answers

  1. # Define the secret password
    SECRET = “abc123”

    # Start the loop
    while True:
    # Prompt the user for a password
    password = input(“Enter password: “)

    # Check if the password matches the secret
    if password == SECRET:
    print(“You got it!”)
    break # Exit the loop if the password is correct
    else:
    print(“Sorry, that did not match. Please try again.”) # Error message for incorrect password

  2. Explanation:

    1. Define the Secret Password:
      • The constant SECRET is set to "abc123".
    2. Infinite Loop:
      • The while True: loop ensures the program continues to prompt the user until the correct password is entered.
    3. Password Check:
      • Each user input is compared to the SECRET. If it matches, the program prints “You got it!” and exits the loop using break.
      • If it doesn’t match, an error message is displayed, and the loop continues.
    4. Output Matches the Sample Run:
      • The program’s behavior mimics the provided sample output exactly.

Related Questions