用Python创建登录系统

时间:2020-10-19 01:42:29

标签: python authentication

所以这是我第一次尝试使用python项目,因此我决定尝试创建一个登录系统。我基本上将其写为一个大的while循环,带有大量的if语句,但我被卡住了,因为当我尝试检查文本文件中是否已经存在用户名时,我不确定如何将用户送回重新输入用户名。另外,我的一些打印语句正在打印多次,但我不确定为什么。所以,实际上我的问题是1:是否有更好/更简洁的方式编写此代码?和2:为什么程序无法正确识别现有用户名并两次打印某些语句(例如“错误:用户名已被使用”)

这是我的代码:

file = open('Login.txt', 'a')
newUser = True

while newUser:
    user = input('Are you a new user? y/n, press q to quit: ')
    if user == 'y':
        print('Create an account.\n')
        newUsername = input('Enter New Username(must be at least 4 characters, no spaces): ')
        #check to make sure the username & password fit the correct criteria
        with open('Login.txt', 'r') as e:
            for line in e:
                loginInfo = line.strip().split(',')
                if newUsername == loginInfo[0]:
                    print('Error: that username is already in use.')
                    break
                elif len(newUsername) < 4:
                    print('Error: Not enough characters.')
                    break
                else:
                    print('Username accepted\n')
                    newUsername = newUsername.strip()
                    newPassword = input('Enter New Password (must be at least 8 characters, no spaces): ')
                    if len(newPassword) < 8:
                        print('Error: Not enough characters.')
                    else:
                        confirmPass = input('Confirm your password: ')
                        if confirmPass == newPassword:
                            print('Account Created')
                            newPassword = newPassword.strip()
                            file.write(newUsername)
                            file.write(',')
                            file.write(newPassword)
                            file.write('\n')
                            file.close()
                            print('Your login details have been saved.')
            
    else:
        newUser = False

    if user == 'n':
    userName = input('Enter your username: ').strip()
    #if the username and password match what is in the text file then they can login successfully   
    with open('Login.txt', 'r') as f:
        for line in f:
            loginInfo = line.strip().split(',')
            if userName == loginInfo[0]:
                passWord = input('Enter your password: ').strip()
                if passWord == loginInfo[1]:
                    print('Login successful')
                else:
                    print('Incorrect password')
            else:
                print('Username does not exist')

    else:
        print('invalid input')
        break
    
#if the user quits, end the program
while not newUser:
    if user == 'q':
        print('Quitting...')
        break

2 个答案:

答案 0 :(得分:1)

现在我真的真的不知道如何追加字典,但是如果您创建帐户并在不关闭程序的情况下登录就可以正常工作

from sys import exit
from os import name, system

users = {}
status = ''

def clear():
    if name == 'nt':       #If Windows clear screen
        _ = system('cls')
    else:                  #If Linux etc. clear screen
        _ = system('clear')

def newUser():
    newUsername = input('Create new username: ')

    if newUsername in users:
        print('\nUsername already exists!\n')
        input('Press [Enter] to continue')
    else:
        newPassword = input('Create new password: ')
        users[newUsername] = newPassword #Append to dictionary(users)
        print('\nAccount created successfully!\n')
        input('Press [Enter] to continue')

def oldUser():
    login = input('Enter username: ')
    password = input('Enter password: ')
    if login in users and users[login] == password: #If user and pass match, continue
        print('\nLogin successful!\n')
        input('Press [Enter] to continue')
    else:
        print('\nLogin failed!\n')
        input('Press [Enter] to continue')

while True:
    clear()
    status = input('Are you a registered user? [y/n] Press [q] to quit\n> ')
    status = status.lower()
    if status == 'y':
        oldUser()
    elif status == 'n':
        newUser()
    elif status == 'q':
        exit()
    else:
        continue

答案 1 :(得分:0)

以下是您应修复的错误:

  1. 同时注册新用户:在Login.txt文件中,您正在逐行进行迭代,因此 当您添加新用户line到达您的newly added details时,现在 执行此块的if newUsername == loginInfo[0]。这就是为什么您应该在每次注册后获得Error: that username is already in use.
  2. 成功注册后,它应退出while循环。
  3. 如果user != 'n',则print('invalid input')始终执行。这就是为什么你应该 在这种情况下总是会得到'invalid input'
  4. 您可以使用if语句退出第一个while循环本身,而不要使用最后一个while循环。