Nested Functions

Nested Functions

Programs for Nested Functions

Program 1: Basic Nested Function for Greeting

def greet(name):
    """Outer function that defines a nested greeting function."""
    def display_message():
        """Inner function to create a greeting message."""
        return f"Hello, {name}!"
    return display_message()

# Example usage
print(greet("Alice"))

Expected Output:

Hello, Alice!

Program 2: Nested Function for Calculating Factorial

def calculate_factorial(n):
    """Outer function to calculate factorial using an inner recursive function."""
    def factorial(x):
        if x == 1:
            return 1
        else:
            return x * factorial(x - 1)
    
    return factorial(n)

# Example usage
print("Factorial of 5:", calculate_factorial(5))

Expected Output:

Factorial of 5: 120

Program 3: Nested Function to Calculate Area and Perimeter of a Rectangle

def rectangle_properties(length, width):
    """Outer function to calculate area and perimeter using nested functions."""
    def area():
        return length * width

    def perimeter():
        return 2 * (length + width)

    return f"Area: {area()}, Perimeter: {perimeter()}"

# Example usage
print(rectangle_properties(5, 3))

Expected Output:

Area: 15, Perimeter: 16

Program 4: Nested Function to Find Maximum of Three Numbers

def find_maximum(a, b, c):
    """Outer function to find the maximum of three numbers using a nested function."""
    def maximum(x, y):
        return x if x > y else y
    
    return maximum(a, maximum(b, c))

# Example usage
print("Maximum of 3, 7, and 5:", find_maximum(3, 7, 5))

Expected Output:

Maximum of 3, 7, and 5: 7

Program 5: Nested Function with Conditional Logic (Palindrome Checker)

def is_palindrome(word):
    """Outer function to check if a word is a palindrome."""
    def reverse(w):
        return w[::-1]
    
    return word == reverse(word)

# Example usage
print("Is 'radar' a palindrome?", is_palindrome("radar"))
print("Is 'hello' a palindrome?", is_palindrome("hello"))

Expected Output:

Is 'radar' a palindrome? True
Is 'hello' a palindrome? False

These examples demonstrate various uses of nested functions, from recursive calculations to helper functions for performing specific tasks within a larger function.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top