0

I'm constantly getting a NameError Although I already defined a term, The problem is with "day" on line 28.

def today():
    day = input("What day is it?")

    if "sunday" in day:
        day = 0
    elif "monday" in day:
        day = 1
    elif "tuesday" in day:
        day = 2
    elif "wednesday" in day:
        day = 3
    elif "thursday" in day:
        day = 4
    elif "friday" in day:
        day = 5
    elif "saturday" in day:
        day = 6

    else:
        today()
today()

days_on_vacation = int(input("How many days will you be on vacation?   "))

days_to_add_to_day = days_on_vacation % 7

day += days_to_add_to_day

I already gave day a value in the function today() right? Why am I being told it is not defined?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
pokemonfan
  • 209
  • 1
  • 2
  • 9

1 Answers1

3

Names you assign to in a function are locals; they are not visible outside of the function.

The best way to share that result is to return the value from the function, so that you can assign it to a variable as a result of the call:

def today():
    # ...
    return day

and

result = today()

The result variable then holds the value the function returned. You are free to use the name day there too but that's then a separate variable from the one inside the function.

You did complicate matters here by using a recursive function call; you then also need to make sure you pass on the result of the recursive calls back along the chain:

def today():
    # ...
    else:
        return today()
    return day

However, it is better not to rely on recursion here; a simple enless loop would do a better; returning from the function would automatically end the loop:

def today():
    while True:
        day = input('...')
        # ...
        else:
            # not valid input, restart the loop
            continue

        # input was valid, return the result
        return day
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • The complete rule is that names you assign to anywhere are local and not visible outside the current local scope unless specified otherwise by `global` or `nonlocal`. This is equally true for class bodies and exec()ed code. Some confusion arises because module locals are also the globals for the module – Terry Jan Reedy Apr 04 '15 at 20:58