简体   繁体   中英

Python error with hello.py traceback

I'm very new to Python. I am having an issue with my hello.py command. It gives me the following error:

C:\Users\Admin>python hello.py
Traceback (most recent call last):
    File "hello.py", line 1 in <module>
        if _name_ == "_main_":
NameError: name '_name_' is not defined

Try using 2 underscores before and after name and main, so:

__name__

And

__main__

Try putting this in your hello.py :

def myfunction():
   print "hello!"

if __name__ == "__main__":
   myfunction():

In other words

Enclose the code you have in the hello.py script in a function wrapper ( myfunction() in above example). Now, when executing hello.py from the command line , the myfunction() will be called by the if __name__ == "__main__": part)


Here's another way

If you want to import hello.py as a Python module in another Python script, say anotherPython.py. Place an empty file in the same directory as the hello.py , whose name is exactly: __init__.py . Then in the anotherPython.py, write:

import hello
hello.myfunction()

That should then print "hello!" when executed in Python.

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