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'
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
if username == 'pi':
return password
That's doing exactly what you tell it: returning the password you entered when you enter pi
as a username.
You probably wanted to do this instead:
if username != 'pi':
return 'restricted'
What is happening is here is very simple.
raw_input('username')
gets the username and puts it in the variable username and same way for password.
After that, there is simply an if condition saying if username is 'pi' then return password. Since you are entering the username 'pi' that's what its doing.
I think you are looking for something like this:
>>> def login():
username = raw_input('username ')
password = raw_input('password ')
if username == 'pi':
if password == '123':
return 'welcome'
elif password == 'guest':
return 'welcome guest'
else:
return 'Please enter the correct password'
else:
print 'restricted'
>>> login()
username pi
password 123
'welcome'
>>> login()
username pi
password guest
'welcome guest'
>>> login()
username pi
password wrongpass
'Please enter the correct password'
精彩评论