it is an exercise in CS61A, this code could work:
def protected_secret(password, secret, num_attempts):
"""
Returns a function which takes in a password and prints the SECRET if the password entered matches
the PASSWORD given to protected_secret. Otherwise it prints "INCORRECT PASSWORD". After NUM_ATTEMPTS
incorrect passwords are entered, the secret is locked and the function should print "SECRET LOCKED".
>>> my_secret = protected_secret("correcthorsebatterystaple", "I love UCB", 2)
>>> my_secret = my_secret("hax0r_1") # 2 attempts left
INCORRECT PASSWORD
>>> my_secret = my_secret("correcthorsebatterystaple")
I love UCB
>>> my_secret = my_secret("hax0r_2") # 1 attempt left
INCORRECT PASSWORD
>>> my_secret = my_secret("hax0r_3") # No attempts left
SECRET LOCKED
>>> my_secret = my_secret("correcthorsebatterystaple")
SECRET LOCKED
"""
def get_secret(password_attempt):
nums = num_attempts
if nums == 0:
print('SECRET LOCKED')
return protected_secret(password, secret, nums)
if password_attempt == password:
print(secret)
return protected_secret(password, secret, nums)
else:
nums -= 1
print('INCORRECT PASSWORD')
return protected_secret(password, secret, nums)
return get_secret
but when writing like the following, it gives error, I dont understand why I can not use variable num_attempts directly in the child function, but I can use password and secret?
def protected_secret(password, secret, num_attempts):
def get_secret(password_attempt):
if num_attempts == 0:
print('SECRET LOCKED')
return protected_secret(password, secret, num_attempts)
if password_attempt == password:
print(secret)
return protected_secret(password, secret, num_attempts)
else:
num_attempts -= 1
print('INCORRECT PASSWORD')
return protected_secret(password, secret, num_attempts)
return get_secret
and when we write code like this, it can worked well:
def f(x,y,z):
def h(q,w,e):
if x > 0:
return x * q + y * w + z * e
else:
return x + y + z + q + w + e
return h