How to call a function?

Hello,

how do we actually call a function in Python? Do we just write its name followed by parenthesis and then go ‘‘run’’, or we have to use print function?

Thank you.

3 Likes

It depends on how you function works.
If your function doesn’t print anything instead it returns the values, then you can use print to print it out to the console:

# using return
def myFunc():
  return "hi"

print myFunc()

But if your function doesn’t return and instead prints it directly inside the function body, then don’t use print:

# printing directly inside the function body
def myFunc():
  print "hello"

myFunc()

Hope this helps :grinning:

3 Likes

Thank you sir, it’s more clear now.

4 Likes

For completeness’ sake, it should be pointed out that that actual calling of the function occurs when the interpreter gets to the “function call”: the function name followed by parentheses which contain appropriate values for the function parameters.

This might occur simply because the function call is the next statement in line to be evaluated, as in the second example above, or it might occur, as in the first example, because the function call is part of a print statement (or print() function in Python3), and must be evaluated before the print statement itself can run.

It also might occur because the function call is on the right side of the assignment operator (=), and the function must be run to obtain a value to assign to a variable.

myGreeting = myFunc()
# do something with myGreeting

Again, the point is that the function is called when the “function call” is encountered by the interpreter as the code is running.

5 Likes

Thank you very much for your answer, very well explained.

3 Likes