Search code examples
pythonraw-inputfunction

Python: login using 1 username but different passwords


I am trying to write a function that will understand how to login using one username but several passwords .

import sys

def login():
    username = raw_input('username')
    password = raw_input('password')

    if username == 'pi':
        return password 
        # if the correct user name is returned 'pi' I want to be
        # prompted to enter a password .
    else:
        # if 'pi' is not entered i want to print out 'restricted'
        print 'restricted'

    if password == '123':
        # if password is '123' want it to grant access
        # aka ' print out 'welcome'
        return 'welcome'

    if password == 'guest':
        # this is where the second password is , if 'guest'
        # is entered want it to grant access to different
        # program aka print 'welcome guest'
        return 'welcome guest'

This is what I get when i run the function.

>>> login()

usernamepi
password123
'123' 

Should be returning 'welcome'

>>> login()

usernamepi
passwordguest
'guest' 

Solution

  • if the correct user name is returned 'pi' I want to be prompted to enter a password.

    Your code prompts for both username and password. Only after that it checks what was entered.

    Assuming you want your login function to return the values and not to print them out, I believe what you want is something like this:

    def login():
        username = raw_input('username: ')
    
        if username != 'pi':
            # if 'pi' is not entered i want to print out 'restricted'
            return 'restricted'
    
        # if the correct user name is returned 'pi' I want to be
        # prompted to enter a password .
        password = raw_input('password: ')
    
        if password == '123':
            # if password is '123' want it to grant access
            # aka ' print out 'welcome'
            return 'welcome'
    
        if password == 'guest':
            # this is where the second password is , if 'guest'
            # is entered want it to grant access to different
            # program aka print 'welcome guest'
            return 'welcome guest'
    
        # wrong password. I believe you might want to return some other value