-3

This code is fully functional without the use of error handling. Is there a more efficient way to write this? I'd love to learn from all of you.

from getpass import getpass

username = input("Username: ")
grant_access = False

while not grant_access:
  password = getpass("Password: ")
  if password == 'pass123':
    grant_access = True
  elif password != 'pass123':
    while not grant_access:
      password = getpass("Re-enter Password: ")
      if password == 'pass123':
        grant_access = True
      elif password != 'pass123':
        continue

print("Logging in...")
  • 5
    This question might be better received on [CodeReview.se]. – Fred Larson Apr 15 '19 at 21:37
  • 1
    Possible duplicate of [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). – martineau Apr 15 '19 at 22:14

1 Answers1

1

You could do it this way:

from getpass import getpass

username = input("Username: ")
password = getpass("Password: ")

if password != 'pass123':
  while True:
    password = getpass("Re-enter Password: ")
    if password == 'pass123':
      break

print("Logging in...")

Or even like this:

from getpass import getpass

username = input("Username: ")
password = getpass("Password: ")

while password != 'pass123':
  password = getpass("Re-enter Password: ")

print("Logging in...")