What you want is a loop, which you break out of as soon as you get the right answers, but otherwise just loop through again.
while True:
name = input('\nEnter username: ');
if name == 'Bradley':
pwd = input('Enter password: ')
if pwd == '1234':
print("\nWelcome," , name, "")
time.sleep(2)
break
print("Invalid username or password")
Now, if the name was 'Bradley' and the password was '1234', you will break
out of that loop. Otherwise, you won't, you'll just do it all again. And since True
is always true, you'll keep doing it forever, until you get the answers you want.
You can do this with any kind of loop, not just a while True
. For example, if you want to give them three chances, and then bail out:
for i in range(3):
name = input('\nEnter username: ');
# etc.
else:
print('Too many tries, go learn how to hack better')
sys.exit(1)
I'd like it so the 'user' doesn't know if they've got a wrong username or password until both have been entered, kind of like a real life scenario.
Then just move the pwd = …
part outside the if name == 'Bradley'
part:
name = input('\nEnter username: ');
pwd = input('Enter password: ')
if name == 'Bradley':
if pwd == '1234':
# etc.
And now that you've done that, you can simplify things:
name = input('\nEnter username: ');
pwd = input('Enter password: ')
if name == 'Bradley' and pwd == '1234':
# etc.
And now that you just have a single if
, you can attach an else
to it, for code that runs unless both name
and pwd
match. (Go back and look at the nested if
statements and you should be able to figure out why it would be hard to add an else
that way.)
name = input('\nEnter username: ');
pwd = input('Enter password: ')
if name == 'Bradley' and pwd == '1234':
# etc.
else:
print("Invalid username or password")