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?

Atinesh
  • 1,790
  • 9
  • 36
  • 57
  • 2
    change `import Prg1` to `from Prg1 import printHello` and you'll be fine – jedwards Mar 10 '15 at 04: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. – Two-Bit Alchemist Mar 10 '15 at 04: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](https://docs.python.org/2/tutorial/modules.html) 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. :-) – Greenonline Apr 08 '15 at 21:10

3 Answers3

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

backtrack
  • 7,996
  • 5
  • 52
  • 99
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()
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
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.

Virbhadrasinh
  • 529
  • 6
  • 19
  • 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` – Atinesh Mar 10 '15 at 05:24
  • but @Atinesh above code i tested in Python 3.X so its working – Virbhadrasinh Mar 10 '15 at 05:26