Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function in a separate file in Python [duplicate]

Tags:

python

module

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?

like image 799
Atinesh Avatar asked Feb 02 '26 15:02

Atinesh


1 Answers

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

like image 138
backtrack Avatar answered Feb 04 '26 05:02

backtrack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!