我正在尝试编写一个函数,该函数将了解如何使用一个用户名登录,但使用多个密码。
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'
这是我运行该功能时得到的结果。
>>> login()
usernamepi
password123
'123'
应该返回'welcome'
>>> login()
usernamepi
passwordguest
'guest'
答案 0 :(得分:4)
如果返回正确的用户名'pi',我希望系统提示您输入密码。
您的代码会提示输入用户名和密码。只有在那之后它才会检查输入的内容。
假设您希望login
函数返回值而不打印它们,我相信您想要的是这样的:
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
答案 1 :(得分:2)
if username == 'pi':
return password
这正是您所说的:返回您输入pi
作为用户名时输入的密码。
您可能想要这样做:
if username != 'pi':
return 'restricted'
答案 2 :(得分:2)
这里发生的事情很简单。
raw_input('username')
获取用户名并将其放入变量用户名,密码也一样。
之后,只有if条件说如果用户名为'pi'则返回密码。由于您输入的是用户名“pi”,这就是它的作用。
我认为你正在寻找这样的东西:
>>> 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'