簡體   English   中英

奇怪的函數調用和不一致的結果

[英]Weird Functions Calling and Inconsistent Result

首先,我只想說我是一個新手,對於糟糕的解釋和長篇大論,我深表歉意......

因此,作為練習,我編寫了一個簡單的 python 登錄系統,其中包含存儲配置文件的 JSON 文件。

一切都很順利,但突然間我的代碼開始表現得很奇怪。 這是我的 main.py 文件:

import json

with open("profiles.json") as f:
    profiles = json.load(f)


def main():
    print("-----------------Main--------------------")
    option = input("[L]ogin | [S]ign up: ").upper()

    if option == "L":
        login()
    elif option == "S":
        sign_up()
    else:
        print("Please select a valid option.")
        main()


def login():
    print("-----------------Login--------------------")

    username = input("Username: ")
    password = input("Password: ")
    check_credentials(username, password)


def sign_up():
    print("-----------------Sign up--------------------")

    new_username = None
    new_password = None

    # check if this username already exists, return to sign up if true
    def username_match():
        nonlocal new_username

        new_username = input("Username: ")

        for profile in profiles["profiles"]:
            if new_username == profile["username"]:
                print("This username is taken.")
                username_match()

    # loop back if the passwords do not match
    def password_match():
        nonlocal new_password

        new_password = input("Password: ")
        confirm_password = input("Confirm Password: ")

        if new_password != confirm_password:
            print("Passwords do not match.")
            password_match()

    username_match()
    password_match()

    security_question = input("Security Question: ")
    security_answer = input("Security Question Answer: ")

    profiles["profiles"].append({"username": new_username,
                                 "password": new_password,
                                 "security_question": security_question,
                                 "security_answer": security_answer})

    with open("profiles.json", "w") as w:
        json.dump(profiles, w, indent=2)

    check_credentials(new_username, new_password)


def profile_settings():
    input("-----------------Options--------------------"
          "\n"
          "[P] change password | [U] change username"
          "\n"
          "[S] change security question | [E] add email"
          "\n"
          "What would you like to do: ").upper()

    print("\nThis section is under construction. Please visit later.")


def check_credentials(username, password):
    print("\nchecking credentials...\n")

    for profile in profiles["profiles"]:

        if profile["username"] != username and profile["password"] != password:
            print("Wrong username and password, please try again.")
            login()

        if profile["username"] == username:
            print(f"found username: {username}")
            if profile["password"] == password:
                print(f"found password: {password}")
            else:
                print("Wrong password, please try again.")
                login()
        else:
            print("Wrong username, please try again.")
            login()

        profile_settings()


main()

這是我的profiles.json文件:

{
  "profiles": [
    {
      "username": "Hakobu",
      "password": "123",
      "security_question": "favorite food",
      "security_answer": "lemon"
    },
    {
      "username": "Mohammed",
      "password": "345",
      "security_question": "1",
      "security_answer": "1"
    }
  ]
}

這是我發現奇怪的地方:

  1. 當我嘗試登錄到第二個配置文件時,它告訴我,憑據錯誤並讓我回到login() function,但它讓我進入第一個配置文件。
  2. 當嘗試通過sign_up() function 創建新配置文件時,它應該自動登錄,但超出第一個配置文件,創建的第二個配置文件只是做同樣的事情,它告訴我,錯誤的憑據並讓我回到login() function。
  3. 當使用第一個配置文件成功登錄時,會調用profile_settings() function。 it's supposed to close after inputing anything, but instead it goes back to the check_credentials() function, says I input the wrong username and password, then going to the login() function straight after the profile_settings() function even though I have not called它們在profile_settings() function 中的任何位置

我不知道為什么會發生這種情況。 就在剛才,它工作得很好。 嘗試注釋掉我在工作后編寫的代碼,但沒有任何效果。 我現在頭疼得厲害,腰也疼。

在了解了堆棧調用和堆棧幀之后,我現在知道問題只是退出check_credentials()后 for 循環恢復,導致 function 似乎是無限循環。

這是改進的代碼:

def check_credentials(username, password):
    print("\nchecking credentials...\n")

    username_found = False
    password_found = False

    for profile in profiles["profiles"]:
        if profile["username"] == username:
            print(f"found username: {username}")
            username_found = True
            if profile["password"] == password:
                print(f"found password: {password}")
                password_found = True
                break

    if not username_found and not password_found:
        print("Wrong username and password, please try again.")
        login()
    elif not username_found:
        print("Wrong username, please try again.")
        login()
    elif not password_found:
        print("Wrong password, please try again.")
        login()

    profile_settings()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM