[英]Login system on Python
這是一個真正的新手問題。 因此,我正在嘗試在Python中編寫一個登錄系統,要求輸入用戶名(僅提供1個用戶名),如果鍵入的用戶名不正確,則說明用戶名無效,如果正確,則要求輸入用戶名。密碼,如果密碼不正確,則表示密碼錯誤,然后再次要求輸入密碼;如果輸入的密碼正確,則僅表示已登錄。
到目前為止,我能夠做的是:
a = 0
while a < 1:
print ('Username:')
name = input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
a = a + 1
password = input()
b = 0
while b < 1:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
b = b + 1
continue
else:
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
break
盡管用戶輸入了錯誤的密碼,但它確實執行了我不希望執行的操作,但它確實可行。 如果用戶輸入了錯誤的密碼,我希望程序告訴用戶“錯誤的密碼”並再次要求輸入,但是它沒有這樣做,它只會打印“錯誤的密碼”,然后終止。 不過,它在要求用戶名的那部分工作100%。
這是我想念的一件事。 我怎樣才能解決這個問題? 非常感謝!
每當用戶輸入錯誤的密碼時,語句b = b + 1
就會終止while
循環。 確實沒有必要。
您也可以將密碼提示包裝在while
循環中:
while input("Enter password") != "1234":
print("Password incorrect")
檢查密碼時不需要+ 1
。 那只是使您脫離循環。
相反,請嘗試:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
continue
一個更好的解決方案是使用布爾值,而不是使用+1
和<1
來打破循環。 樣品:
userCorrect = False
while not userCorrect:
print ('Username:')
name = raw_input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
userCorrect = True
password = raw_input()
passCorrect = False
while not passCorrect:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
print ('Password:')
password = raw_input()
else:
passCorrect = True
# Since password is correct, continue.
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
輸入無效密碼后,此循環( while b < 1:
)終止。
看着
> if password != '1234': #checks the password typed in
> print ('Password incorrect.')
> b = b + 1
> continue
代碼行b = b + 1
使得while b < 1:
時為假,從而結束了循環並終止了程序。
正如其他人已經指出,問題出在b = b + 1
打破了條件while b < 1:
使其不要問另一個密碼。 簡單刪除行b = b + 1
使用getpass()
而不是input()
來避免“過肩”攻擊。 您的密碼輸入被屏蔽為****
恩。
from getpass import getpass
password = getpass()
Cryptify
嗯,除了聽起來很酷之外,這並沒有真正阻止某些人修改代碼以跳過密碼階段,但是可以阻止他們看到代碼中的原始密碼。
這篇文章使用passlib
有一個很好的例子
這有助於保護非唯一/敏感的密碼(例如您用於5倍其他密碼的密碼,或者您母親的娘家姓……請勿將其拖入其中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.