1

我正在尝试编写一个函数,该函数将了解如何使用一个用户名但多个密码登录。

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' 

应该返回“欢迎”

>>> login()

usernamepi
passwordguest
'guest' 
4

3 回答 3

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
于 2011-08-04T22:07:51.480 回答
2
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'
于 2011-08-04T21:56:24.877 回答
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'
于 2011-08-04T22:07:32.290 回答