简体   繁体   中英

Enthought Canopy python - name ' ' not defined

I'm very new to using canopy and programming in general.

I'm trying to define a function in Python in the canopy editor. This used to work for me but has suddenly stopped and I have no idea why.

As a basic example, in the editor I wrote;

def funct(x):
    return x

When write funct(1) in the shell I get the error message

NameError: name 'funct' is not defined

Any ideas? Thanks

You need to "run" your script (in the editor) before its results actually exist (and are visible in) the Python shell. In this case the results of your script are to define your function. Just writing the function in the editor doesn't actually create it in Python until you run the script.

As Ali correctly said, another (deeper) approach is to import the script (in this case known as a module), but I think running is probably more what you have in mind.

I've never used Canopy before, but in general you would save the file where your function is defined somewhere in your working directory (eg as myfunct.py ), then import it into the shell namespace:

In  [1]: import myfunct

In  [2]: myfunct.funct(1)
Out [2]: 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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