NameErrors and functions in python

橙三吉。 提交于 2019-12-12 06:17:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!