Here’s another article in the Functions in Python series. Today we’ll be talking about calling functions in other functions. If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
10) Arbitrary Number of Both Positional and Keyword Parameters
11) Nested Functions
We can call a function inside another function. Let’s define 2 simple functions:
def trim_string(text, length):
if len(text) > length:
return text[:length]
else:
return text
def repeat_trimmed_string(text, length, repetitions):
trimmed_text = trim_string(text, length) + " "
return trimmed_text * repetitions
print(repeat_trimmed_string("interesting", 5, 7))
The second function, repeat_trimmed_string, calls the first function in its body. Here’s the result:
inter inter inter inter inter inter inter