python - 最后几行代码中的无限 while 循环

标签 python loops while-loop infinite-loop

有人可以帮我解决以下问题吗:

我有一个代码可以读取用户名和密码,然后允许用户访问程序。我有第一个选项来注册新用户正确。我的最后两行代码遇到无限循环问题。我想运行一个字符串,说明如果输入了未注册的用户名,它将返回一个字符串,说明没有这样的注册用户。该字符串只是在循环中继续运行,我可以做些什么来改变它。

username: admin

password: adm1n

我的代码如下:

users = {}  
with open ('user.txt', 'rt')as username:
    for line in username:
        username, password = line.split(",")
        users[username.strip()] = password.strip()  # strip removes leading/trailing whitespaces

uinput = input("Please enter your username:\n")
while uinput not in users:
    print("Username incorrect.")
    uinput = input("Please enter a valid username:/n")

if uinput in users:
            print ("Username correct")

with open('user.txt', 'rt') as password:
    for line in password:
        username, password = line.split(",")
        users[password.strip()] = username.strip()  # strip removes leading/trailing whitespaces

uinput2 = input("Please enter your password:\n")
while uinput2 not in users:
    print("Your username is correct but your password is incorrect.")
    uinput2 = input("Please enter a valid password:\n")

if uinput2 in users:
    password2 = ("Password correct")
    print (password2)

if password2 == ("Password correct"):
       menu = (input("\nPlease select one of the following options:\nr - register user\na - add task\nva - view all tasks\nvm - view my tasks\ne - exit\n"))
    if menu == "r" or menu == "R":
                new_user = (input("Please enter a new user name:\n"))
                new_password = (input("Please enter a new password:\n"))
                with open ('user.txt', 'a')as username:
                        username.write("\n" + new_user + ", " + new_password)
    elif menu == "a" or menu == "A":
                task = input("Please enter the username of the person the task is asigned to.\n")
        while task not in username:
                print("User not registered. Please enter a valid username:\n")

最佳答案

最后有一个循环,上面写着

while task not in username:
    print("User not registered. Please enter a valid username:\n")

这是未完成的,并且将无限循环,因为如果 task 不在 username 中,打印某些内容不会改变这一事实,因此它只会循环并再次打印。您可能想添加类似的内容

task = input("Please enter a valid username of a person the task is assigned to.\n")

关于python - 最后几行代码中的无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900023/

相关文章:

python - 我试图在两次之间循环,从 8 :00 to 17:00 for every 15 mins

Python 3 中的 Python 2 打印功能

C - 如何读取输入

javascript - 为什么这个 while 循环会导致无限循环?

php - 从 mysql_fetch_row() 中排除结果

Python - 如何从嵌套列表中获取所有可能的组合

Python Pandas Groupby 根据索引重置值

actionscript-3 - 在这种情况下如何循环 timelinemax 动画

java - java中运算符优先级的本质

java - 为什么要将 && 更改为 ||导致变量不可见