0

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
3
  • 2
    Use double underscores, not just one: __name__ etc. Commented Feb 26, 2017 at 17:41
  • 1
    That's awesome! Thank you - it worked perfectly! Commented Feb 26, 2017 at 18:17
  • 1
    @tonya-nichols You got good ansver. But would be good to show Your hello.py Commented Feb 26, 2017 at 19:02

2 Answers 2

2

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

__name__

And

__main__
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@TonyaNichols I have provided two possibilities, let me know how it goes. But I have, for now, also flagged the question for migration to Stack Overflow. I also tried to remove sentimental statements from your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.