Practical Example: Modular Programming & Function Anatomy

Refactoring Monolithic Code into Modular Functions

Problem Statement: The following code calculates the area of a rectangle and prints it in a single block. Refactor this code by creating a reusable function to calculate the area, demonstrating modular programming and function anatomy.
length = 5
width = 10
area = length * width
print(f"The area is {area}")

Step-by-Step Solution

0 of 4 Steps Completed
1

Practical Example: Variable Scope and Lifetime

Tracing Local vs. Global Variables

Problem Statement: Analyze the following Python code. Predict what will be printed at each step and identify the scope of variables x and y.
x = 10  # Line 1

def my_function():
    y = 5   # Line 4
    x = 20  # Line 5
    print("Inside function x:", x)
    print("Inside function y:", y)

my_function()
print("Outside function x:", x)
# print(y) would cause an error here

Step-by-Step Solution

0 of 4 Steps Completed
1

Practical Example: Parameter Passing and Recursion

Pass-by-Value vs Pass-by-Reference in Lists (Python)

Problem Statement: In Python, integers are immutable (behaving like pass-by-value), while lists are mutable (behaving like pass-by-reference). Demonstrate how a function modifies a list passed as an argument.

Step-by-Step Solution

0 of 3 Steps Completed
1

Tracing a Recursive Function (Factorial)

Problem Statement: Trace the execution of the recursive function factorial(3) to determine the final return value. The function is defined as:
def factorial(n):
    if n == 1:
        return 1  # Base Case
    else:
        return n * factorial(n - 1)  # Recursive Case

Step-by-Step Solution

0 of 4 Steps Completed
1