问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/29447713/nameerrors-and-functions-in-python