The Less Rubbish Password Program

This is an example mini-program to demonstrate the use of an if ... else statement and a while loop.

We previously created a rubbish password program using the following code.

# The Really Rubbish Password Program

# This is the stored password for the user
secret_password = "secret"

print("Welcome to NOSA Inc.")
print("Did you know that the Moon is an average of 238,855 miles away from Earth\n")

password = input("Please enter your password:\n")

if password == secret_password:
  print("\nAccess Granted!")
else:
  print("\nAccess Denied!")

input("\n\nPress the enter key to exit.")

Aside from this being very insecure, a major issue is that the user only gets one guess at entering their password.

1. Improving with a Loop

To improve our program we can add a while loop that repeats the block of code.

password = input("Please enter your password:\n")

if password == "secret":
  print("\nAccess Granted!")
else:
  print("\nAccess Denied!")

To do this we add a boolean variable named access which will track whether the user has access to the system. We then set this to True within the if statement when access is granted.

1.1. The Complete Program

# The Less Rubbish Password Program

# This is the stored password for the user
secret_password = "secret"
access = False

print("Welcome to NOSA Inc.")
print("Did you know that the Moon is an average of 238,855 miles away from Earth")

while not access:
  password = input("\nPlease enter your password:\n")

  if password == "secret":
    print("\nAccess Granted!")
    access = True
  else:
    print("\nAccess Denied!")

input("\n\nPress the enter key to exit.")