2017-03-10 3 views
-1

ユーザーの入力資格情報とテキストファイルに格納されている資格情報を比較するログインプログラムを作成しようとしています。
これを正しく行うにはどうすればよいですか?ログイン機能をシミュレートするプログラムを作成する

これは私がこれまでにやっていることです:

file = open("logindata.txt", "r") 
data_list = file.readlines() 
file.close() 
print(data_list) 


for i in range(0, len(data_list)): 
     username = input("username: ")   
     password = input("password: ")  
     i += 1 
     if i % 2 == 0: 
      if data_list[i] == username and data_list[i + 1] == password: 
      print("You are successfully logged in as", username) 
      i == len(data_list) 
     elif data_list[i] == username and data_list[i + 1] != password: 
      print("The password you entered was incorrect, please try again.")  
     else: # how do i end the code if the user inputs no 
      if data_list[i] != username: 
       choice = input("The username you entered was not found, would you like to create an account? (Y/N)") 
       if choice.upper() == "Y":  
        new_username = input("new username: ")  
        data_list.append(new_username + "\n")  
        new_password = input("new password: ")  
        data_list.append(new_password + "\n")  
        file = open("logindata.txt", "w")  
        file.writelines(data_list)  
        i == data_list  

これは、資格のテキストファイルが設定されている方法です。

user1 
pass1 
user2 
pass2 

答えて

1

私はあなたがこのような何かをしたいと思う:

def does_username_exists(username, login_file_path): 
    username_exists = False 
    user_password = None 
    with open(login_file_path) as login_file: 
    while True: 
     username_line = login_file.readline() 
     if not username_line: break 
     password_line = login_file.readline() 
     if not password_line: break 
     if username == username_line.strip(): 
     username_exists = True 
     user_password = password_line.strip() 
     break 

    return username_exists, user_password 


def main(): 
    login_file_path = "logindata.txt" 

    username = input("Enter username: ") 
    username_exists, user_password = does_username_exists(username, login_file_path) 
    if not username_exists: 
    choice = input("The username you entered was not found, would you like to create an account? (Y/N)") 
    if choice.upper() == 'Y': 
     new_username = input("Enter new username: ") 
     new_password = input("Enter new password: ") 
     with open(login_file_path, "a") as login_file: 
     login_file.write(new_username + "\n") 
     login_file.write(new_password + "\n") 
    return 

    password = input("Enter password: ") 
    if not (password == user_password): 
    print("The password you entered was incorrect, please try again.") 
    else: 
    print("You are successfully logged in as - '{}'".format(username)) 


if __name__ == "__main__": 
    main() 
+0

ありがとうございます!これは多くの助けた –

+0

これはあなたの問題を解決した場合は、答えを受け入れることによって質問を閉じてください。 –

関連する問題