gpt4 book ai didi

python - 用户名/密码程序的打印语句不正确

转载 作者:行者123 更新时间:2023-12-01 05:29:20 28 4
gpt4 key购买 nike

def login():
UserName = input("Please enter your username: ")
passw = input("Please enter your password: ")
check(UserName, passw)
if check(UserName, passw) == True:
print("Thank you for logging in. Please enjoy these lyrics")
else:
print("Sorry, either your username or password is incorrect")

def check(UserName, passw):
pword = {}
for line in open('unames_passwords.txt','r'):
user, password = line.split()
pword[user] = password
if user == UserName and password == passw:
return True
else:
return False


def main():
login()

我当前代码遇到的问题是,仅当我输入文件中包含的名字和密码时,它才会打印 if True, print 语句,但如果我在文件中输入任何其他名称和密码同一个文件,它总是打印在 else 下发出的语句。有人知道我做错了什么吗?

最佳答案

您仅根据密码文件的第一行check()返回。如果第一个密码不匹配,则立即返回 False

return False 移出循环,以便仅在扫描整个文件时执行:

def check(UserName, passw):
for line in open('unames_passwords.txt','r'):
user, password = line.split()
if user == UserName and password == passw:
return True

return False

我在这里删除了pword字典处理;您的代码实际上并没有使用它。

可能希望避免每次登录时调用check()两次,并且您不必测试== Trueif 语句已经为您进行了测试:

def login():
UserName = input("Please enter your username: ")
passw = input("Please enter your password: ")
if check(UserName, passw):
print("Thank you for logging in. Please enjoy these lyrics")
else:
print("Sorry, either your username or password is incorrect")

关于python - 用户名/密码程序的打印语句不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642821/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com