输入任何用户名和密码(不管是否正确)后,它会继续打印另一部分代码。
登录部分工作正常,但之后未显示正确的输出。它不断显示: “输入了错误的登录详细信息 你有帐号吗? 是或否”
这让我和我的老师都感到困惑。我用登录/注册系统的示例浏览了不同的网站。我也尝试过以不同的方式重新排列代码。
这是代码:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("Usernames.txt","r")
found = False
for line in file:
user = line.split(",")
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while ans not in ("Yes", "No"):
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
elif ans == "No":
print("Would you like to make an account? ")
else:
ans = input("Please enter Yes or No ")
用户名和密码正确时的预期结果:
Username: Smartic
~~~~~
Welcome to the game, Smartic
用户名和密码不正确时的预期结果:
Incorrect login details entered
Have you made an account?
Yes or No
用户输入Yes
时的预期结果:
Please sign in again
Please enter your correct username:
Please enter your correct password:
用户输入No
时的预期结果:
Would you like to make an account?
用户输入Yes
或No
以外的内容时的预期结果:
Please enter Yes or No
答案 0 :(得分:0)
无论输入什么用户名,都不能满足文件中的每个用户名。每次都没有,您的错误文本将被打印。按照this question中的说明重新设置代码格式。
答案 1 :(得分:0)
更改您的:
while ans not in ("Yes", "No"):
在:
while True:
此外,我建议创建一个函数。
正如约翰·戈登(John Gordon)提到的使用中断,因此您的脚本将如下所示:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
user = {0:'e',1:'w'}
found = False
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while True:
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
break
elif ans == "No":
print("Would you like to make an account? ")
break
else:
ans = input("Please enter Yes or No ")
break
答案 2 :(得分:0)
文件中每一行的末尾都有一个新行。您可以使用strip()函数删除换行符。
if user[0] == username and user[1].strip() == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])