1

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

それはあなたが言うことを正確に行っています:ユーザー名として入力したときに入力したパスワードを返しpiます。

あなたはおそらく代わりにこれをしたかったでしょう:

if username != 'pi':
    return 'restricted'
于 2011-08-04T21:56:24.877 に答える
2

ここで起こっていることは非常に単純です。

raw_input('username')ユーザー名を取得し、それを変数usernameに入れ、パスワードも同じようにします。

その後、ユーザー名が「pi」の場合はパスワードを返すというif条件があります。ユーザー名「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 に答える