I have a function and I'm making another one in which I need to call the first function. I don't have experience in Python, but I know that in languages like MATLAB it's possible as long as they're in the same directory.
A basic example:
def square(x):
square = x * x
(and saved)
Now in my new function I want to use the function square I tried:
def something (y, z)
import square
something = square(y) + square(z)
return something
Which displays: builtins.TypeError: 'module' object is not callable
.
What should I do?
A function call is an expression that passes control and arguments (if any) to a function and has the form: expression (expression-listopt) where expression is a function name or evaluates to a function address and expression-list is a list of expressions (separated by commas).
You call the function by typing its name and putting a value in parentheses. This value is sent to the function's parameter.
We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.
How to call a function in python? Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
No need for import
if its in the same file.
Just call square
from the something
function.
def square(x):
square = x * x
return square
def something (y, z)
something = square(y) + square(z)
return something
More simply:
def square(x):
return x * x
def something (y, z)
return square(y) + square(z)
If, and only if, you have the square
function defined in a square
module, then you should look to import the simple name from it instead.
from square import square
If you don't want to change anything, then you need to use its fully qualified name:
something = square.square(y) + square.square(z)
The module's name is square
, and you can't call functions on modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With