我如何让这个简单的python登录程序循环?

时间:2019-04-13 17:54:22

标签: python python-3.x python-requests

这是我第一次发布有关堆栈溢出的信息,如果有人可以通过简单的循环功能帮助我,我将不胜感激。这个项目原本是一个4人一组的项目,但是我却大失所望,没有团队的支持。

我是python的完整入门者,非常感谢您的任何帮助或建议。

我试图弄乱并合并一个循环,但我感到自己不甚了解。

当前程序正常工作,并提取.txt文件中的用户名和密码(格式为用户名,密码),但这是测验程序的开始。如果输入了错误的用户名/密码,则用户仍然可以开始测验。

login_username = input('username: ')
login_password = input('password: ')
found_username = False

with open('passwords.txt', 'r') as password_file:
    for line in password_file:
        username, password = line.strip().split(',')

        if login_username == username:
            found_username = True
            if login_password == password:
                print('success!')
            else:
                print('login failure!')
            break

if not found_username:
    print('username invalid')

我将非常感谢任何支持:)

2 个答案:

答案 0 :(得分:0)

您有几种选择。只要尚未输入正确的密码,最基本的密码就会保持。这也意味着对现有代码进行最少的编辑。

logged_in = False #Defines if user is logged in or not
while not logged_in:
    login_username = input('username: ')
    login_password = input('password: ')
    found_username = False

    with open('passwords.txt', 'r') as password_file:
        for line in password_file:
            username, password = line.strip().split(',')

            if login_username == username:
                found_username = True
                if login_password == password:
                    print('success!')
                    logged_in = True #We're not logged in, so loop will exit
                else:
                    print('login failure!')
                break

    if not found_username:
        print('username invalid')

这将不断重复询问usernamepassword,因此更好的版本可能是将username(和用户名检查)放入另一个while环。

希望这会有所帮助!

答案 1 :(得分:0)

首先,我将所有用户名和密码输入字典 其次,我使用while循环来不断要求用户放入正确的usernamepassword

found_username = False
user_dict = {}
#Add username and password into a user dictionary (or library)
with open('passwords.txt', 'r') as password_file:
    for line in password_file:
        username, password = line.strip().split(',')
        user_dict[username] = password
while found_username == False: #keep asking until correct username and password
    login_username = input('username: ')
    login_password = input('password: ')
    #Check input username and password
    for user in user_dict:
        if login_username == user: #check username
            no_username_found = False
            if login_password == user_dict[user]: #check password
                print('success!')
                found_username = True  #accept
                no_username_found = False
                break   #stop when password is correct
            else:
                print('login failure!') #wrong password
                found_username = False
                break  #stop when password is wrong
        else:
            no_username_found = True    

    if no_username_found == True: #check if usename is not found
        print('username invalid') 

print(found_username)