python - 最后几行代码中的无限while循环
问题描述
谁能帮我解决以下问题:
我有一个读取用户名和密码的代码,然后允许用户访问程序。我有第一个选择正确注册新用户。我的最后两行代码遇到了无限循环问题。我想运行一个字符串,说明如果输入了未注册的用户名,它会返回一个字符串,表示没有这样的注册用户。字符串一直在循环中运行,我可以做些什么来改变它。
用户名:管理员
密码: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")
推荐阅读
- android - 自动调整 TextView 的大小不适合更新的文本
- java - Google HTTP 库 JSON 解析,空值默认为 True
- c++ - 与纯 V8 相比,NodeJS 是否有任何性能缺点或显着开销?
- eclipse - 由于非法包名导致的 Javadoc 错误
- pyomo - 如何使用 Pyomo 制作指标函数?
- oracle - Oracle SQL:用可变长度的星号序列替换数字
- arrays - Array#push 导致大型数组出现“堆栈级别太深”错误
- javascript - 无效的 Chai 属性:matchSnapshot
- c# - c#在循环中声明未知数量的矩阵
- javascript - 如果连接,AJAX 中的 JSON 结果未定义