首页 > 解决方案 > 在程序中注册帐户

问题描述

我想为用户创建帐户,因此当他们输入他的个人代码时,程序会回复他的姓名和信息并继续使用该应用程序,到目前为止我有这个但我不知道如何编码。

print("Welcome to xxApp")

YourCode = input("Create your Code: ")
    if Yourcode in Users.txt
        #Continue with the program
    else
        Name = input("Please enter your name: ")
        Age = input("Enter your age: ")
        print(",Name,,YourCode,,Age,"your info has been saved")
        #and continue with the program

标签: pythonpython-3.xoptimizationuser-accounts

解决方案


我不确定使用文本文件是否是最好的主意 - CSV 可能会更好。但是,这适用于使用文本文件。

主要.py:

def accounts():
    yourCode = input("Please enter your user code. \nIf you already have an account, type your account user code. \nOtherwise, enter a new one to create an account: ") # User types their code

    # Opens file of users in read mode
    with open("users.txt", "r") as rf:
        users = rf.readlines() # Creates a list of users in the .txt file to check
        # Checks each user in the file to see if they are already in the accounts list. Each user is split into their user_code, name and age
        for each_user in [user.split(",") for user in users]: 
            if each_user[0] == yourCode: # If the user is in the accounts list
                print(f"Welcome {each_user[1]}") # f{} string allows the name to be inserted easily into the print statement
                xxApp() # Program runs
                return None # Exit Statement to get out of the accounts function when the main program has finished
    # If the user reaches this stage, it means they are not in the account list
    with open("users.txt", "a") as af: # Open file in append
        name = input("Please enter your name: ")
        age = input("Enter your age: ")
        af.write(f"{yourCode},{name},{age}\n") # Adds the users info to the users.txt file
        print(f"Thank you {name}, your information has been added.")
        xxApp()


def xxApp():
    ... # Put your main program here


accounts()

程序运行后的 users.txt 如下所示: 程序运行

NewUser1,Example,27

推荐阅读