0

I'm new to Python and learning at my own speed in my spare time, however, so far, this is the part of my program I am having trouble with:

name = input('\nEnter username: ');
if name == 'Bradley':
    pwd = input('Enter password: ')
    if pwd == '1234':
                print("\nWelcome," , name, "")
                time.sleep(2)

command = input("\nEnter Command: ");

The code itself works fine, however, is it possible to have something along the lines of, if it isn't 'Bradley' or '1234', then print 'Invalid username or password', and then make it loop back to that part of the code. Essentially it's a local logon script.

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
dynastyuk
  • 9
  • 2

1 Answers1

4

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")
abarnert
  • 354,177
  • 51
  • 601
  • 671