## Friday 16 February 2024

### Function Calling Another Function in Python

Function Calling Another Function in Python

To have one function call another, just place the function call within the body of the first function. Here's a simple illustration:

Python

def greet(name):
print("Hello,", name + "!")

def introduce():
name = input("Enter your name: ")
greet(name)  # introduce() calls greet()

introduce()  # Start the program execution

Explanation

1. greet(): Takes a name and prints a greeting.

2. introduce(): Gets the user's name and calls greet() to display the greeting.

3. Program flow: You call introduce(), which in turn calls greet().

Key Benefits

• Modularity: Break your code into smaller, self-contained units, making it easier to manage and debug.

• Reusability: Write functions that can be called from multiple places in your code, avoiding duplication.

• Abstraction: Focus on the high-level logic of what a function needs to do instead of getting buried in implementation details in every part of your program.

Example: Factorial calculation

Python

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1# Recursive call

result = factorial(5)
print(result)  # Output: 120

Important Considerations

• Return Values: A function can return a value, and this returned value can be used by the calling function:
Python
return x + y

print(result)  # Output: 8

• Recursion: A function can call itself (recursion), elegantly solving problems like calculating factorials or the Fibonacci sequence.

.

Example 1: Area Calculator

Python

def calculate_rectangle_area(length, width):
return length * width

def calculate_triangle_area(base, height):
return 0.5 * base * height

def get_shape_area():
shape = input("Enter shape (rectangle or triangle): ")

if shape == "rectangle":
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = calculate_rectangle_area(length, width)
elif shape == "triangle":
base = float(input("Enter base: "))
height = float(input("Enter height: "))
area = calculate_triangle_area(base, height)
else:
print("Invalid shape")
return

print("The area is:", area)

get_shape_area()

Example 2: User Authentication

Python

# Replace with your actual authentication logic
return True
else:
return False

else:
print("Invalid credentials.")

Example 3: Recursive Fibonacci Sequence

Python

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

nterms = int(input("Enter number of terms in Fibonacci sequence: "))

if nterms <= 0:
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i))

11 Function Calling Another Function and Recursion in Python -11 Data Analyst training Telugu