局部变量在python中没有被使用
我正在用python制作一个登录系统,获取用户名,然后检查文本文件上的一行,然后检查下一行,直到找到它,然后检查第二个文件(密码文件)上的同一行,并用用户名确认密码。当我尝试登录一个帐户时,我让它不断循环,直到它自己断开。它找不到的变量是checkusername函数中的第行局部变量在python中没有被使用,python,Python,我正在用python制作一个登录系统,获取用户名,然后检查文本文件上的一行,然后检查下一行,直到找到它,然后检查第二个文件(密码文件)上的同一行,并用用户名确认密码。当我尝试登录一个帐户时,我让它不断循环,直到它自己断开。它找不到的变量是checkusername函数中的第行 u = open('user', 'r+') p = open('password', 'r+') def main(): accountcheck() def accountcheck(): # che
u = open('user', 'r+')
p = open('password', 'r+')
def main():
accountcheck()
def accountcheck(): # check if the user has an account
account = input('Do you have an account?\n')
if account == 'yes':
new = 0
username(new)
elif account == 'no':
new = 1
username(new)
else:
print(account, 'Is not a valid answer. Please try again')
accountcheck()
def username(new): # input username
userlist = u.read().splitlines()
user = input('Please enter your username\n')
if user in userlist and new == 0:
checkuser(user, new)
elif new == 1 and user not in userlist:
password(user, new)
elif new == 1 and user in userlist:
print('Username taken')
username(new)
else:
print('Username is not fount in our database. Please try again')
username(new)
def checkuser(user, new): # scan the username file for the username
line = 1
ulines = u.readlines(line)
if user != ulines:
line = line + 1
checkuser(user, new)
elif ulines == user:
password(user, new)
def password(user, new):
passwordlist = p.read().splitlines()
password = input('Please enter your username\n')
if password in passwordlist and password != user:
checkpassword(user, new, password)
elif new == 1 and password != user:
writelogin(user, password)
else:
print('Password is incorrect. Please try again')
password(user, new)
def checkpassword(user, line, new, password):
plines = p.readlines(line)
if plines != password:
line = line + 1
elif plines == password:
if new == 1:
writelogin(user, password)
else:
print('you have logged in')
def writelogin(user, password):
userwrite = user + '\n'
passwordwrite = password + '\n'
u.write(userwrite)
p.write(passwordwrite)
main()
如果要运行此文件,需要将用户文本文件和密码文本文件放在程序所在的同一文件夹中。在使用递归时,任何帮助都是值得感激的:在您的例子中,checkuser()方法的第一行中的'line'值总是被设置为'1'。这意味着,如果用户不匹配(无限),它将始终读取第一行,并始终再次调用checkuser() 最好使用一个简单的循环 您可能希望将“line”传递给checkuser()方法,例如:
def checkuser(user, new, line=1):
...
我发现您的代码存在以下问题:
read
s时,您总是得到相同的结果,但事实并非如此,当您执行u.read()
第一次获得文件的全部内容时,没有什么神秘之处,但如果您执行u.read()
同样,你什么也得不到,这是因为文件对象内部有一个读取指针,指示它在文件中的位置,当你进行任何类型的读取时,你可以将其视为文本编辑器中跳动的|
,指针根据你执行的读取类型移动,如果是readline
,则移动到下一行;如果是read
或readlines
,则移动到文件的末尾,并且您从操作中获得的是上一位置和新位置之间的所有内容。但是不要担心,有一种方法可以告诉它,在任何读取之前,使用seek
方法将say指针放在哪里,返回到start dou.seek(0)
,以便始终从您的读取中获得相同的结果文档:如果您提供更多信息,您可能会更幸运地得到问题的答案;例如,错误发生在哪一行?您可以粘贴stacktrace以获得更多上下文。您的问题中似乎给出了一个错误的函数名,因为我无法将
checkusername
视为您代码中的函数。因此,我应该在函数外部声明行,然后调用它,只需让line=line+1?@CodyRoberts在这个示例代码行中,当调用为checkuser(user,new)时,默认值为1
,在该函数中,将不同的line值传递给下一个递归调用,例如checkuser(user,new,line+1)
。但我同意@ChrisC73的说法,即您应该使用loopso checkuser(user,new,line+1)在运行function@CodyRoberts:正确;不过,您需要删除方法中的“line=1”声明。