2017-10-12 53 views
-2
def checked(input, correct): 
if input == correct: 
    return True 
else: 
    return False 

while True: 
    try: 
     user_typed = str(raw_input('Type password\n')) 
     password = str('test') 
     number_of_trys = 0 
    if checked(user_typed, password) is True and number_of_trys <= 3: 
     print('Welcome User') 
     break 
    else: 
     print("Password is incorrect, please try again.") 
     number_of_trys += 1 
     print(number_of_trys) 
finally: 
    print('Loop Complete') 

我嘗試打印「number_of_trys」,但它一直輸出「1」。是的,我試過做number_of_trys = number_of_trys + 1。嘗試將1添加到變量並打印它,但它輸出相同的數字

+0

'number_of_trys = 0'在每個while循環中重置了您的變量。將它移到 –

+0

之外請閱讀[在什麼情況下,我可以在我的問題中添加「緊急」或其他類似短語,以獲得更快的答案?](// meta.stackoverflow.com/q/326569) - 總之是,這不是解決志願者問題的理想方式,而且可能適得其反。請不要將這添加到您的問題。 – halfer

+0

'def checked'縮進比它看起來非常錯誤的材料更多。如果它是錯誤的,你會在你的問題中解決這個問題嗎? – halfer

回答

0

每次你在try:中要求輸入密碼時,你都要將number_of_trys設置爲0.在while循環之外聲明它並將它重置爲if語句

def checked(input, correct): 
    if input == correct: 
     return True 
    else: 
     return False 

number_of_trys = 0 

while True: 
    try: 
     user_typed = str(raw_input('Type password\n')) 
     password = str('test') 
    if checked(user_typed, password) is True and number_of_trys <= 3: 
     print('Welcome User') 
     number_of_trys = 0 
     break 
    else: 
     print("Password is incorrect, please try again.") 
     number_of_trys += 1 
     print(number_of_trys) 
finally: 
    print('Loop Complete') 
+0

好的謝謝你的幫助! – purplefuzzkd

相關問題