Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a function in a function?

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?

like image 705
Jane.0 Avatar asked Oct 05 '15 22:10

Jane.0


People also ask

What is it called when a function calls a function?

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).

How do you call a function in?

You call the function by typing its name and putting a value in parentheses. This value is sent to the function's parameter.

Can I define a function inside a function?

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.

Can you call a function in a function Python?

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.


Video Answer


2 Answers

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)
like image 162
Ty Pavicich Avatar answered Sep 18 '22 18:09

Ty Pavicich


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.

like image 28
Makoto Avatar answered Sep 22 '22 18:09

Makoto