3

I've seen this type of topic already answered. But none of the answers, I've seen seem to work for me. because I think its related to different version of Python. The tutorial I'm watching uses Python2.x and the code is working fine in Python 2.x. But I'm using Python 3.x and It's not working in Python 3.x.

I am just trying to call a function in separate file. But when I run the main program file, i.e. mainPrg.py, I'm stuck with this error message.

NameError: name 'printHello' is not defined

Prg1.py

def printHello():
    print("Hello Son")
    input()

mainPrg.py

import Prg1

printHello()

Is there any problem with my code?

3
  • 2
    change import Prg1 to from Prg1 import printHello and you'll be fine Commented Mar 10, 2015 at 4:46
  • 1
    To whomever upvoted this: Please consider looking for a duplicate to flag next time instead. This question (a.) has been asked here numerous times in various forms, and (b.) could be trivially solved by reading the fabulous manual, any number of tutorials, or any number of StackOverflow questions already answered. Commented Mar 10, 2015 at 4:56
  • @Two-BitAlchemist - I was the upvoter... because I had the exact same issue, and it was the first question and answer that google presented me with a solution that fixed my issue. I was in a hurry to complete a task, the manual made no sense to me in my stressed state (in my current relaxed state, it does now), and unfortunately time constraints did not afford me the luxury of being able to search for duplicates. Apologies. :-) Commented Apr 8, 2015 at 21:10

3 Answers 3

4
def printHello():
    print("Hello Son")
    input()

Change the import like below

from Prg1 import printHello

printHello()

Check this : https://docs.python.org/2/tutorial/modules.html

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

Comments

2

If you import the entire module then you need to call the module before the function. So it should look like this:

import Prg1

Prg1.printHello()

1 Comment

4 leading spaces == monospace formatting & syntax highlighting, for future reference ;)
1
  • After analysis Your problem
  • In your second file when you want to call method must do this

     import Prg1
     Prg1.printHello()
    

Any Problem with that must comment me.

2 Comments

I was watching a video tutorial from Youtube. In that tutorial, the guy was using Python 2.x IDLE and I'm using Python 3.x IDLE. Is this a problem, I've seen that lots of syntax has been changed in Python 3.x
but @Atinesh above code i tested in Python 3.X so its working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.