【发布时间】:2023-04-11 06:41:01
【问题描述】:
第一次在这里发帖,虽然我已经潜伏多年了
我目前正在从事一个编程项目并且被卡住了。该项目的目标是获取用户的输入、用户名和密码,并通过文本文件验证是否正确。如果正确,它将打印“欢迎!”最后,如果没有,它会询问用户名和密码并循环,直到输入正确的组合。
文本文件格式如下:
达斯:维达
波巴:费特
R2:D2
欧比旺:克诺比
卢克:天行者
这是我的代码:
# Lets user know what this program will do
print("Please login");
# Opens accounts txt file
accounts_file = open("accounts.txt", "r")
# Flag to terminate while loop
complete = False
# Runs loop until username and password are correct
while complete == False:
# Asks user for username and stores as variable
usernameInput = input("Username:");
# Asks user for password and stores as variable
passwordInput = input("Password:");
# Reads each line of the text file line by line
# Darth:Vader
# Luke:Skywalker
# R2:D2
# ObiWan:Kenobi
# Boba:Fett
for line in accounts_file:
# Stores each line in file as a username/password combo
username, password = line.replace("\n","").split(":")
# If username and password match, breaks out of the loop and sets complete to True
if usernameInput == username and passwordInput == password:
complete = True
break
# Sets complete to False and loops back
else:
complete = False
continue
if complete == True:
print("Welcome!");
如果第一次输入正确的名称,我可以让它正确运行: 例如:
请登录:
用户名:达斯
密码:维达
欢迎!
- 结束程序
如果我输入了错误的名字,它会像这样循环回来:
请登录:
用户名:达斯
密码:费特
用户名:.....
但是,如果我输入了错误的用户名,然后又输入了正确的用户名,它不会像我想要的那样结束程序,并继续循环:示例:
请登录:
用户名:Luke 密码:Vader
用户名:Darth 密码:Vader
用户名:R2 密码:D2
知道是什么导致它不接受用户的下一个输入并完成循环吗?
感谢您的帮助!
【问题讨论】:
-
我不确定,但可能文件迭代器在第一次迭代中已经用尽,所以当你进入第二次尝试时,没有更多的行了。也许尝试而不是使用文件处理程序将所有行存储在带有
.readlines()的列表中。 -
顺便说一下,
Sets complete to False and loops back部分是不必要的。您不需要将complete设置为False,因为它已经是False。如果它是 True 你已经结束了 for 循环和 while 循环。而且您不需要continue,因为您将在到达 for 循环末尾后自动继续。
标签: python