How do you call a function in a function?

后端 未结 4 1558
耶瑟儿~
耶瑟儿~ 2020-12-18 06:56

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

相关标签:
4条回答
  • 2020-12-18 07:03

    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)
    
    0 讨论(0)
  • 2020-12-18 07:09

    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.

    0 讨论(0)
  • 2020-12-18 07:22

    2 way to use a function within an other:

    1. You define the square() function in another .py file (ex: myfile.py) and then, you can import the function this way:
    from myfile import square
    
    def newFunction():
       square()
    
    1. You define the function in the same file and then there is no need for the import and you can use square() directly.
    0 讨论(0)
  • 2020-12-18 07:23

    You have several options.

    1. Put everything in one file. Then you only need to call the other function; forget about all imports then.

    2. Put the square function in a different file, e. g. foo.py. Then your using function needs to import it. For that you have two options again: import foo and use foo.square(y) or from foo import square and use square(y). (You can name your module like your function as well -- the two have separate name spaces -- so then you would have to from square import square.)

    Modules (i. e. in a separate file) are used for grouping logically connected things together, e. g. all mathematical functions, all operating-system related things, all random number generator related things, etc. So in your case which looks like a first test I'd propose to put everything in one file and forget about all imports.

    0 讨论(0)
提交回复
热议问题