Nested Functions in Python
To shorten the code, you can nest functions within each other when calling them.
Let's say we have functions for squaring a number, cubed a number, and summing two numbers:
def square(num):
return num ** 2
def cube(num):
return num ** 3
def add(num1, num2):
return num1 + num2
To get the sum of the square and cube of a number, we can put them into the add function parameter when calling it:
res = add(square(2), cube(4))
print(res) # 68
You can also call functions within the body of another function. Let's rewrite the previous example and call functions inside add:
def add(num1, num2):
return square(num1) + cube(num2)
res = add(2, 4)
print(res) # 68
Make a function that will square a number and a function to get the cube of a number. Also, using them, create a function to display the cube of the square of a number.
Make a function that will check the variable type and if the variable is a string, then print it with a capital letter. Also create a function that will greet the user by name. Nest the first function in it so that the name is always printed with a capital letter.