pavlov
pavlov

Reputation: 121

Spyder (python 2.7) - why do scripts run if I hit run button, but not if I type script name in command line?

New to python/spyder. I am having trouble running scripts the way I want to. Quck example using the following script:

# Demo file for Spyder Tutorial
# Hans Fangohr, University of Southampton, UK

def hello():
    """Print "Hello World" and return None"""
    print("Hello World")

# main program starts here
hello()

I have saved this as hello.py. When I type hello() into my command line, I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined

However, if I hit the run button with this script open in the Editor, it runs just fine, and prints Hello World. I can then type hello() into my command line and it runs just fine.

Could someone please explain to me why this is?

My general goal is to save a startup.py script that I can run from the default cwd, which changes my cwd to where I want to save all of my code.

Upvotes: -1

Views: 429

Answers (1)

kindall
kindall

Reputation: 184151

hello isn't defined until you execute the def hello statement. You haven't run the script yet so that line hasn't been executed. After you have run the script, hello has been defined.

Upvotes: 2

Related Questions