授予的访问权限未在第三次尝试中出现

时间:2019-01-23 22:10:30

标签: python-3.x

在最后一次尝试中,如果输入了正确的密码,则程序退出前不会出现“授予访问权限”的字样

AccessGranted = False
attempt = 1
password = input("Please enter your password: ")
while (attempt < 3) and (AccessGranted == False):
           if password == "compScience":
                      AccessGranted = True
                      print("Access granted")

           else:
                      password = input("Incorrect password -  re-enter: ")
                      attempt = attempt +1

1 个答案:

答案 0 :(得分:0)

在else语句内进行第三次输入尝试后,attempt等于3,然后循环结束(您不应将输入放在else内)。这就是程序退出并且不显示任何内容的原因。如果您只想尝试3次,我认为以下代码会更好:

AccessGranted = False
attempt = 1
while (attempt < 4) and (AccessGranted == False):
    password = input("Password: ")
    if password == "compScience":
        AccessGranted = True
        print("Access granted")
    else:
        print("Incorrect password. ")
        attempt = attempt + 1

您可以看到我将输入放置在while循环内,并且为了允许3次尝试,停止条件变为attempt < 4