简体   繁体   English

在IDLE中出现NameError问题-Python

[英]Trouble with NameError in IDLE - Python

got some trouble with my selfmade code. 我的自制代码遇到了一些麻烦。

def even(a, b):
    f = []
    while a <= b:
        if a % 2 == 0:
            f.append(a)
        a = a + 1
    return f;

When i'm tryin to call it from the shell it says: 当我尝试从外壳调用它时,它说:

Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
even(0,200)
NameError: name 'even' is not defined.

I think it's not a really tricky problem, but can u help my anyway? 我认为这不是一个真正棘手的问题,但是您仍然可以帮助我吗? Thank you up front. 谢谢你。 Cheers 干杯

Two things. 两件事情。 Are you indenting your function correctly and how are you calling your function? 您是否正确缩进了函数以及如何调用函数? the following code works: 以下代码有效:

def even(a, b):
    f = []
    while a <= b:
        if a % 2 == 0:
            f.append(a)
        a = a + 1
    return f;

print(even(2,3))
#output: [2]

Notice the indentation and the fact that even is being called after it is defined. 注意缩进以及定义后甚至被调用的事实。

Edit: I notice you've gotten it working, now would be a good time to refacter some parts of your function ie give the variable fa more descriptive name. 编辑:我注意到您已经开始使用它了,现在将是重新了解函数某些部分的好时机,即为变量fa提供更具描述性的名称。

If you want to run it from your shell, you would want to: 如果要从外壳程序运行它,则需要:

  1. enter python into shell, to start your python interpreter 在外壳中输入python ,以启动python解释器
  2. enter from <your-code's-filename.py> import even from <your-code's-filename.py> import even

then you can use the function as you tried: even(0,200) 那么您可以尝试使用该函数: even(0,200)

But you can also just run it from within IDLE like Wright suggests. 但是您也可以像Wright所建议的那样在IDLE中运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM