Print() is a function, but is being called inside another function. Is this okay?

Question

Within the context of this exercise, we placed a print() function within another function. Is it okay to place function calls inside another function?

Answer

Yes, you have functions calls within another function. You can think of functions as generally being a collection of multiple lines of code. These lines can be statements, expressions, and even other function calls.

When you run a function that calls another function, it will go through its code lines as usual, and when it gets to the function call, it will complete that call, and then continue with its next lines of code as usual.

Example

def sayHi():
  print("Hi!")

def sayWords():
  sayHi() # The function call will run and complete.

  # After the function call above completes, then Python
  # will continue with the next code lines in the function.
  print("How are you?")
28 Likes

def Hello world ()
print("Hello"0

Hi, Marty – Not sure if you posted a question here, but here are a couple of comments:

To post code, use the </> icon that is found in the middle of the menu bar at the top of the text box you are typing in.

def Hello world ()
    print("Hello")

There are a couple of syntax errors (or typos) here, along with one style error. The style error is that we generally do not begin function names with uppercase letters. Can you find the syntax errors?

11 Likes

Hello um, how would i know when the function ends after so it doesn’t repeat any code i’m doing.

2 Likes

A Python function ends when the indentation is removed.

def foo():
    # code body

print (foo())    # this line is not in the code body of the function
17 Likes

are there any conditions regarding the order of declaration of the functions?

eg : If one function has to be called within another function, the function should be predefined? or declaring the called function after the function call is okay?

Consider this example…

from functools import reduce

reduce(mul, [1,2,3,4,5,6,7])

def mul(a, b):
    return a * b

When we run it we get,

Traceback (most recent call last):
  File "C:/Users/../Python38/Scripts/func_order.py", line 2, in <module>
    reduce(mul, [1,2,3,4,5,6,7])
NameError: name 'mul' is not defined
>>> 

That should answer your question. Calling a function before the definition will result in a NameError.

Hey, I tried to create a function by adding “+” two functions that I previously defined, but an error came.

Is it impossible, or am I doing something wrong :blush: ?