Fays Fays - 1 month ago 4
Python Question

A first use of python function

Sorry for the very silly question. I am a self-study beginner in python and I am having issues with using a function and calling it. I am coming from a MATLAB background so i was trying to do something similar.

Tools used: Python 2 in a Linux environment

As a test, I created a function that i called prthis (for "print this") within a file called also prthis.py. This function just takes a number as an input, and then outputs two numbers, respectively the same one and its square. I defined it like this:

#----------------------------------------
# content of the file prthis.py
#----------------------------------------

def prthis(x):

y=x*x

nb=x

return (y, nb)
#------------------------------------------


then, within the python prompt, I try to call the newly created prthis function, and I do this:

>>> import prthis

>>> g,t = prthis(7)


The import seems to be succesful, but when I try the function on two outputs variable called g and t , like above, i get the following error message:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable


Perhaps I am too much MATLAB-izing my thinking. Does anyone has a suggestion on how to deal with this?

PS: it's my first question ever on stackexchange, so please could you let me know how to thank/accept valuable answers from other users? I do not wish to look like ungrateful to those who would try to help.

Answer

you are importing a module, not the function. If you want to import just the function you could do this:

from prthis import prthis
g,t = prthis(7)

but if you import the full module you have to call the function as well:

import prthis
g,t = prthis.prthis(7)
Comments