[英]How to make last element in python for loop increment one last time
[英]How do I make "if the loop is executing for the last time" condition in python
所以,我正在通過python中的文件處理來制作登錄系統。 當我輸入正確的用戶名/密碼時,代碼工作正常,但當我使用“else”語句作為用戶輸入錯誤密碼時應執行的條件時,它不起作用。
for line in open('accounts.txt','r+').readlines():
loginfo = line.split()
if a==loginfo[0] and b==loginfo[1]:
return render(request, 'login.html')
else:
return render(request, 'index.html')
這里不需要標志或獨特的功能:
# use a with block to ensure the file will be properly closed
with open("accounts.txt") as file:
# files are their own iterators, no need to read the
# whole file in memory
for line in file:
# get rid of newlines / trailing whitespaces etc
loginfo = line.strip().split()
if a==loginfo[0] and b==loginfo[1]:
return render(request, 'login.html')
# if a match has been found, we'll never get here,
# so if we get here no match has been found...
return render(request, 'index.html')
現在我不得不說將登錄數據存儲在文本文件中是有史以來最糟糕的想法,特別是當 Django 作為一個完整、安全、工作且非常易於使用的身份驗證/用戶系統時。
您的文本文件有很多行,每一行都匹配一個特定的帳戶。 您所做的錯誤是您在循環內返回False
,這是錯誤的,因為您必須遍歷所有行。 之后你可以只返回False
因為沒有帳戶匹配登錄名和密碼
def check_login():
for line in open('accounts.txt','r+').readlines():
loginfo = line.split()
if a==loginfo[0] and b==loginfo[1]:
return True
return False
def login_view(request):
if check_login():
return render(request, 'index.html')
else:
return render(request, 'login.html')
for line in file:
loginfo = line.strip().split()
if a==loginfo[0] and b==loginfo[1]:
return render(request, 'login.html')
return render(request, 'index.html')
注意:- 這應該應用於distinct usernames
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.