2

Why can't I change the variable reminder at

reminder = "oops"

In this code:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            reminder = "oops"
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

ask_ok("what")

ask_ok("again")
Sebastian
  • 33
  • 3

1 Answers1

1

You can't change the default value of the parameter by assigning to it. Assigning to it just changes its value in the current call, it's not a permanent change to the function.

If you want a persistent variable, use a global variable.

reminder = 'Please try again!'

def ask_ok(prompt, retries=4):
    global reminder
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            reminder = "oops"
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)
Barmar
  • 741,623
  • 53
  • 500
  • 612