Python中的名称错误和函数 [英] NameErrors and functions in python

查看:146
本文介绍了Python中的名称错误和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  def today():
day = input(它是哪一天?)

如果在星期日为星期日:
day = 0
elif daydayin day:
day = 1
eliftuesdayin day:
day = 2
elifwednesdayin day:
day = 3
elifthursdayin day:
day = 4
eliffridayin day:
day = 5
elifsaturdayin day:
day = 6

else:
today()
today()

days_on_vacation = int(input(你会度假多少天))

days_to_add_to_day = days_on_vacation%7

day + = days_to_add_to_day

我已经给函数 today()赋值了一天吗?为什么我被告知它没有被定义?

解决方案

您在函数中分配的名称是 locals ;它们在函数之外是不可见的。



分享这个结果的最好方法是从函数中返回值,这样你可以将它分配给一个变量作为调用的结果:

$ $ p $ def today():
#...
回报日

 result = today()

result 变量然后保存函数返回的值。您可以自由使用名称 day 那里,但那是一个与函数内部的变量分离的变量。



你通过使用递归函数调用使事情变得复杂;您还需要确保将递归调用的结果传递回链中:

  def today(): 
#...
else:
今天返回()
返回日

但是,最好不要在这里依赖递归;一个简单的无限循环会做得更好;

  def today():
而真:
day = input('...')
#...
else:
#无效输入,重启循环
continue

#输入有效,返回结果
返回日


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?

解决方案

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

这篇关于Python中的名称错误和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆