2017-02-13 40 views
0

我的問題是:我怎樣才能限制密碼的錯誤介紹並將其作爲一個函數?限制密碼在python中的介紹

我想在範圍

if password == (password1): 
    print('Please wait') 
    print('Correct, logging in.') 
    exit 

for password in range(5): 
    if password != (password1): 
     print('Please wait') 
     print('Incorrected, closing program.') 

     exit 

做它,但它作爲重複循環5次。

+0

如果密碼正確,只是「破」!並且不要使用'password'作爲你的範圍變量,因爲它是一個整數! –

+3

你把**分配給'password'嗎?你叫'input()'?什麼是「退出」?這肯定不是你的整個計劃。 https://stackoverflow.com/help/mcve –

+0

你有兩個問題的近距離投票,說「不清楚你在問什麼」。請[編輯問題](http://stackoverflow.com/review/suggested-edits/15198806)並澄清您的要求,否則將由社區關閉。 –

回答

0

也許你正在尋找這方面的東西?我不太確定!該程序將允許您在退出前輸入5次錯誤的密碼。

password1 = "hello" 


i=0 
while i<=4: 
    password = raw_input("Enter password: ") 
    if password1 == password: 
     print "Welcome" 
     break 
    else: 
     print "Try Again. %d tries left" %(4-i) 
     i+=1 
else: 
    print "oops, you ran out of tries" 
0

範圍內循環使用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內置庫隱藏密碼因此有人看着你的肩膀看不到你輸入的內容。隨機睡眠/等待是一個安全措施的例子,它有助於防止用戶使用計時攻擊(不是它可能會幫助你在這種情況下)。