[Tutor] Using import

Peter Otten __peter__ at web.de
Sun May 4 10:09:50 CEST 2014


Felipe Melo wrote:

[Felipe, please post plain text, your code examples are unreadable]

> Hello,
> I'm starting with Python and I'm trying to work with "import" but I'm
> having a problem. I have the file c.py (that works when executed) with a
> function performing a multiplication:
> def mult(a,x):	resul=a*x        return(resul)print 'test
> print'ent1=2ent3=3dedo=mult(ent1,ent3)print 'result: ',dedo
> 
> and I have the file b.py that calls c.py but should only print a sentence,
> without use the function in c.py (I tried to use the code without the
> comment part but got the problem, my goal is to use b.py with the
> commented part being part of the code): import c ent1=2ent2=7print
> 'testing b.py without any operation'
> #saida=c.mult(ent1,ent2)#print 'the output is:',saida
> 
> 
> 
> My problem is when I execute b.py, it executes c.py before b.py:
> $ python b.py test printresult:  6testing b.py without any operation
> 
> 
> 
> How should I work with this? What I want is use the function defined in
> c.py inside b.py


You can prevent code from being executed on import by adding 

if __name__ == "__main__": 
    ... # executed only when run as a script

Example:

$ cat hello.py
def hello(name):
    print("Hello, {}".format(name))

if __name__ == "__main__":
    hello("Peter")
$ python hello.py
Hello, Peter
$ cat hello_felipe.py
import hello

if __name__ == "__main__":
    hello.hello("Felipe")
$ python hello_felipe.py 
Hello, Felipe




More information about the Tutor mailing list