範圍內循環使用for ...,您可以要求用戶在循環的開始重新進入,
from getpass import getpass
import random
import sys
import time
def validate_user_password(password, attempts=5):
for attempts_remaining in reversed(range(attempts)):
prompt='Please enter the password ({} attempts remaining): '.format(attempts_remaining + 1)
entry = getpass(prompt=prompt)
print('Please wait...')
# Wait random amount between 0.5s and 1s
time.sleep(random.uniform(0.5, 1))
if entry == password:
print('Correct, logging in.')
return True
else:
print('Incorrect password.')
# All attempts failed
return False
if __name__ == '__main__':
password = 'chewbacca'
if validate_user_password(password):
print('Admin powers unlocked. Here are the rocket launch codes: 1-2-3-4-5')
else:
print('Closing program.')
sys.exit(-1)
注:將getpass內置庫隱藏密碼因此有人看着你的肩膀看不到你輸入的內容。隨機睡眠/等待是一個安全措施的例子,它有助於防止用戶使用計時攻擊(不是它可能會幫助你在這種情況下)。
如果密碼正確,只是「破」!並且不要使用'password'作爲你的範圍變量,因爲它是一個整數! –
你把**分配給'password'嗎?你叫'input()'?什麼是「退出」?這肯定不是你的整個計劃。 https://stackoverflow.com/help/mcve –
你有兩個問題的近距離投票,說「不清楚你在問什麼」。請[編輯問題](http://stackoverflow.com/review/suggested-edits/15198806)並澄清您的要求,否則將由社區關閉。 –