尝试将1添加到变量并打印,但输出相同的数字

时间:2017-10-12 01:12:58

标签: python

    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 :(得分: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')