1

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
Junhe
  • 11
  • 1
  • If an assignment like e. g. the `num_attempts -= 1` is present, the variable is seen as local to the (inner) function. You have to declare it "nonlocal" in the inner function to avoid that. – Michael Butscher Apr 19 '22 at 03:12
  • I don't know if you can see it, thank you very much! – Junhe Apr 19 '22 at 03:57
  • An @ followed by the name (like @Junhe) ensures that the mentioned person will be notified. If the poster of the question comments and there is only one poster of comments above him (like here) the commenter will also be notified. – Michael Butscher Apr 19 '22 at 04:29

0 Answers0