1

I really want to learn how do I repeat my code when its statement is false in Python. I just wanna know, how do I make Python ask for username and password again if its wrong? Here is my code:

print("Enter username")
username = input()
print("Enter password")
pword = input()
if username=="Shadow" and pword=="ItzShadow":
   print("Access granted to Shadow!")
else:
   print("Wrong username and / or password")

I meant, how can I make Python ask for Username and Password again if one of it is false?

Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

4

You need to enclose your code in a loop. Something like this:

def get_user_pass():
   print("Enter username")
   username = input()
   print("Enter password")
   pword = input()
   return username, pword

username, pword = get_user_pass()
while not(username=="Shadow" and pword=="ItzShadow"):
   print("Wrong username and / or password")
   username, pword = get_user_pass()

print("Access granted to Shadow!")
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
2

Use a while loop:

while True:
    print("Enter username")
    username = input()
    print("Enter password")
    pword = input()
    if username=="Shadow" and pword=="ItzShadow":
        print("Access granted to Shadow!")
        break # Exit the loop
    else:
        print("Wrong username and / or password") # Will repeat

stuff() # Only executed when authenticated
fecavy
  • 185
  • 2
  • 12
0

We are using the data entering function get_input in the loop each time the user and password aren't same.

def get_input():
# enter your declarations here
return [user_name,password]

user,pwd=get_input()
while (user!='your desired user' and pwd!='the password'):
    print('Not authorized')
    user,pwd=get_input()
print('Your success message')
soundslikeodd
  • 1,078
  • 3
  • 19
  • 32