Python用户名和密码登录while和for循环

时间:2016-01-20 11:45:14

标签: csv for-loop login while-loop python-3.4

我有一个学校作业,要为医院制作一个登录程序(我们必须制作一个电子卫生保健系统)。但我的代码的问题是它只检查每个.csv行一次。每当我第一次登录错误时,它就会停止循环,我无法再登录了。它还会检查每一行并打印出错误的那一行。如何修复我的代码,以便在填写错误的登录信息后仍然可以登录?

import csv


def login():
    print('Welcome to the eHealth program, please sign in')

    with open('users.csv') as csvfile:
        database = csv.DictReader(csvfile)
        loggedin = False
        while loggedin is not True:
            Username = input('Fill in your username: ')
            Password = input('Fill in your password: ')
            for row in database:
                Username_File = row['username']
                Password_File = row['password']
                Function_File = row['function']
                if (Username_File == Username and
                    Password_File == Password and
                        Function_File == 'patient'):
                    loggedin = True
                    print('Succesfully logged in as a patient.')
                    # patientmenu()  # we will add this later on
                elif (Username_File == Username and
                      Password_File == Password and
                        Function_File == 'arts'):
                    loggedin = True
                    print('Succesfully logged in as a doctor.')
                    # artsmenu()     # we will add this later on
                elif Username_File != Username and Password_File == Password:
                    # loggedin = False
                    print('Failed to sign in, wrong username.')
                elif Username_File == Username and Password_File != Password:
                    # loggedin = False
                    print('Failed to sign in, wrong password.')
                elif Username_File != Username and Password_File != Password:
                    # loggedin = False
                    print('Failed to sign in, wrong username and password.')
               else:
                    print('Error 404, Login Not Found')

# ---- Main ---- #
login()

csv文件中的那个示例:(对于这种情况并不重要)

username,password,function
patient1,patient1,patient
patient2,patient2,patient
arts1,arts1,arts
arts2,arts2,arts

我已经尝试通过将open打开到while循环来修复它,但是然后又出现了另一个问题。现在它每次打印4行,如果你正确登录,它会在成功登录时打印1行,用错误的用户名和密码打印3行。

import csv

def login():
    print('Welcome to the eHealth program, please sign in')

    loggedin = False
    while loggedin != True:
        Username = input('Fill in your username: ')
        Password = input('Fill in your password: ')
        with open ('users.csv') as csvfile:
            database = csv.DictReader(csvfile)
            for row in database:
                Username_File = row['username']
                print(Username_File)
                Password_File = row['password']
                print(Password_File)
                Function_File = row['function']
                print(Function_File)
                if Username_File == Username and Password_File == Password and Function_File == 'patient':
                    loggedin = True
                    print('Succesfully logged in as a patient.')
                elif Username_File == Username and Password_File == Password and Function_File == 'arts':
                    loggedin = True
                    print('Succesfully logged in as a doctor.')
                elif Username_File != Username and Password_File == Password:
                    loggedin = False
                    print('Failed to sign in, wrong username.')
                elif Username_File == Username and Password_File != Password:
                    loggedin = False
                    print('Failed to sign in, wrong password.')
                elif Username_File != Username and Password_File != Password:
                    loggedin = False
                    print('Failed to sign in, wrong username and password.')
                else:
                    print('Error 404, Login Not Found')

login()

2 个答案:

答案 0 :(得分:1)

我建议您构建一个数据库,在程序启动时使用cvs内容提供字典。

之后,您可以创建循环以检查此词典并在其上应用逻辑。

此链接可能可以帮助您理解python词典:http://www.tutorialspoint.com/python/python_dictionary.htm

答案 1 :(得分:0)

所以这里发生了什么:

你的while循环保持活动状态,但是在循环csv文件中的所有行之后,你再也不能进入for循环,因为没有剩下的行可以循环。如果你想修复它,你需要找到一种方法来处理最后一行后重置for循环。

正如Roberto Alcantara在他的回答中所建议的,一个更优雅的解决方案是在你进入你的while循环之前构建包含所有用户名,密码和函数的3个数据集,然后你可以检查以下几行:

if username in usernames:
    do some stuff
else:
    do some other stuff

这将允许您在while循环中执行此操作,而无需一直迭代csv读取器实例。

我还冒昧地修复了一些格式化的东西,这些东西在你的代码中并不是真正的pythonic(虽然不是真的错误)。

编辑:

这里有一些我很快拼凑在一起的东西,它并不像它想要的那样好,因为它再一次循环创建数据库的内容,但至少它有效:

import csv


def login():
    print('Welcome to the eHealth program, please sign in')

    with open('users.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        database = []
        for row in reader:
            database.append(dict(username=row['username'],
                                 password=row['password'],
                                 function=row['function']))

    loggedin = False
    while not loggedin:
        Username = input('Fill in your username: ')
        Password = input('Fill in your password: ')
        for row in database:
            Username_File = row['username']
            Password_File = row['password']
            Function_File = row['function']
            if (Username_File == Username and
                Password_File == Password and
                    Function_File == 'patient'):
                loggedin = True
                print('Succesfully logged in as a patient.')
            elif (Username_File == Username and
                  Password_File == Password and
                    Function_File == 'arts'):
                loggedin = True
                print('Succesfully logged in as a doctor.')
        if loggedin is not True:
            print ('Failed to sign in, wrong username or password.')

# ---- Main ---- #
login()

我确定这里的一些python向导可以提出一个巧妙使用数据类型的解决方案,这样你仍然可以链接用户名,密码和角色,而不必循环,但它可以完成工作。

我想提出另一件事:

正如您可能已经看到的那样,我删除了指示是否找到密码的打印件,但用户名错误,反之亦然。它极大地破坏了安全性,暗示用户名或密码是否在您的数据库中得分,即使登录不成功,所以除非您的任务明确要求,否则我会留下。另一方面,当您以明文存储密码时,谈论安全性是没有意义的。 ; - )