Python程序在循环之后结束

M21*_*081 0 python python-3.x

我试图用python登录系统.要登录,您必须先注册.注册后,将其存储到文本文件中,密码为base64.然后,如果您登录它,则要求输入密码被编码到base64中的用户名和密码,并根据文本文档进行检查.但是当它搜索密码时没有任何反应.它只是结束程序并转到shell.没有回溯错误或任何事情.好像其余的代码是不可见的.代码如下:

try:
    import linecache
    import base64
    import tkinter
    import time
    choice = ""
    def choose():
        choice = input("Would you liek to register or login: ")
        choice = choice.upper()
        if choice == "REGISTER":
            f = open("h.txt", "a")
            f.write("\n")
            print("Please enetr a username")
            username = input(">>> ")
            print("Please enter a password")
            passw = input(">>> ")
            print("\n"*100)
            passw_conf = input("Please enter your password again\n>>> ")
            print("\n"*100)
            if passw == passw_conf:
                print("Thank you for Registering")
                f.write(username + "\n")
                passw = base64.b64encode(passw.encode('utf-8'))
                passw = str(passw)[2:-1]
                f.write(passw + "\n")
                f.close()
                choose()
            else:
                print("Please choose register again as passwords do not match.")
        elif choice == "LOGIN":
            username = input("Please enter your username\n>>> ")
            passw = input("Please enter your password\n>>> ")

            x = 0
            with open("h.txt") as f:
                    lines = [line.rstrip('\n') for line in open('h.txt')]
            while lines[x] != username:

                print(lines[x])
                if lines == username:
                    print("Got it ;)")
                elif lines != username:
                    print("Not got it ;(")
            passw = base64.b64encode(passw.encode('utf-8'))
            passw = str(passw)[2:-1]
            if passw == lines:
                print("Logged in successfully")
            elif lines == "":
                print("Username not found!")
    choose()
except KeyboardInterrupt:
    print("Restarting....")
    time.sleep(8)
    print("\n"*100)
    choose()
    choose()
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

您的代码存在许多问题.它仅适用于第一个用户名h.txt是输入的用户名,否则您将拥有无限循环.第二,lines是一个列表,所以永远不等于passwd或"".因此没有任何内容.

它应该如下所示:

    username = input("Please enter your username\n>>> ")
    passw = input("Please enter your password\n>>> ")

    with open("h.txt") as f:
        lines = [line.rstrip('\n') for line in f]
    for line in lines:
        if line == username:
            user_password = next(lines)
            break
    else:
        print("Username not found!")
        return
    passw = base64.b64encode(passw.encode('utf-8'))
    passw = passw[2:-1]
    if passw == user_password:
        print("Logged in successfully")
    else:
        print("Wrong password")
Run Code Online (Sandbox Code Playgroud)