2011-08-04 12 views
1

私は1つのユーザー名で複数のパスワードを使ってログインする方法を理解する関数を書こうとしています。Python: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' 

これは私が機能を実行するときに得られるものです。ユーザー名としてpiを入力するときに入力したパスワードを返す:

>>> login() 

usernamepi 
password123 
'123' 

は、あなたがそれを言うかを正確にやっている「歓迎」

>>> login() 

usernamepi 
passwordguest 
'guest' 
+0

ので、我々は何を理解することができ、コードのタグを使用して書式設定を修正してください続行中です。 – utdemir

+0

ごめんなさい。それは私の最初の投稿 – PythagorasPi

答えて

4

お客様のコードには、ユーザー名とパスワードの両方が入力されます。それ以降は、入力された内容をチェックします。

私が何をしたいことは、このようなものであると信じて、あなたがそれらをプリントアウトして値を返すとしないように、あなたの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 
+0

パーフェクトでした。あなたは私の問題を完全に理解しました。はい、私は間違ったパスワードを残しました。私はちょうどやるだろう – PythagorasPi

2
if username == 'pi': 
    return password 

を返すされなければなりません。

おそらく、代わりにこれをやってみたかった。何が起こっている

if username != 'pi': 
    return 'restricted' 
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' 
関連する問題