Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Building a Square Footage Calculator with Functions in Python: A Step-by-Step Lab Guide

Learn how to build a Python program that calculates total home square footage using functions and function composition. This guide walks through prompt_user, room_square_feet, and main functions with clear examples.

Python functions function composition square footage calculator CSCI 141 lab Python programming tutorial accumulator pattern prompt_user function room_square_feet total square footage Python Python input conversion Python docstring example function decomposition Python main guard coding best practices Python Python lab assignment help Python for beginners

Introduction: Why Functions Matter in Real-World Programming

In programming, functions are the building blocks that let you avoid repeating yourself. Imagine you're working for a construction company that builds homes with square or rectangular rooms. You need to calculate the total square footage of a house—maybe for pricing materials or planning layouts. Instead of writing the same input and calculation code over and over for each room, you can create reusable functions. This lab from CSCI 141 (Spring 2019) teaches you exactly that: how to decompose a problem into three functions—prompt_user, room_square_feet, and main—and compose them to solve a practical task.

Think of functions like the apps on your phone. Each app does one thing: messaging, maps, camera. When you need to book a ride, your ride-sharing app composes those functions (maps + payment + messaging) to deliver a result. Similarly, your Python program will compose functions to compute square footage efficiently.

Understanding the Assignment: Three Functions Only

The lab specifies that your program must have exactly three functions:

  1. prompt_user: Takes two arguments (a question string and a return type) and returns the user's input converted to that type.
  2. room_square_feet: Takes a room shape (square or rectangle) and returns the square footage by calling prompt_user for dimensions.
  3. main: Asks for the number of rooms, loops through each room, calls room_square_feet, and accumulates the total.

This structure mirrors real-world software design: small, testable functions that do one thing well. Let's build each one step by step.

Step 1: Writing the prompt_user Function

The prompt_user function handles all user interaction. It prints a question, gets input, and converts it to the desired type. According to the lab, it must work for both strings and integers (and potentially floats).

def prompt_user(question, return_type):
    """Prompt the user with a question and return input as the specified type."""
    user_input = input("What is the " + question + "? ")
    if return_type == "integer":
        return int(user_input)
    elif return_type == "float":
        return float(user_input)
    else:
        return user_input

Notice the docstring explains purpose and behavior. This function is generic—you can reuse it for any prompt. For example, to ask for the number of rooms, you'd call prompt_user("number of rooms", "integer"). The output will be an integer ready for math.

Testing in the interactive shell: After writing this function, test it by calling prompt_user("shape of room 1", "string") and entering "square". You should get back the string "square". Similarly, test with "integer" to ensure conversion works.

Step 2: Building room_square_feet

This function calculates the area of one room. It receives the shape (already determined by main) and uses prompt_user to get dimensions. For a square, it asks for side length once; for a rectangle, it asks for length and width.

def room_square_feet(shape):
    """Return the square footage of a room given its shape."""
    if shape == "square":
        side = prompt_user("side length of square room", "integer")
        return side * side
    else:  # rectangle
        length = prompt_user("length of the room", "integer")
        width = prompt_user("width of the room", "integer")
        return length * width

This function composes prompt_user—it calls it once or twice depending on the shape. The lab emphasizes that you should not repeat prompt logic; let the function do the work. This is function composition in action: a higher-level function (room_square_feet) uses a lower-level one (prompt_user) to get its job done.

Step 3: Implementing main with the Accumulator Pattern

The main function ties everything together. It asks for the number of rooms, then loops that many times. For each room, it asks for the shape, calls room_square_feet, and adds the result to a running total. This is the classic accumulator pattern (see Section 6.4 of the textbook).

def main():
    """Calculate total square footage of a home."""
    total = 0
    num_rooms = prompt_user("number of rooms", "integer")
    for i in range(1, num_rooms + 1):
        shape = prompt_user("shape of room " + str(i), "string")
        total += room_square_feet(shape)
    print("The total square footage is", total)

Notice the loop starts at 1 to match the sample output. The main function does not return anything; it just prints the final total. To make the program run, add the main guard at the bottom:

if __name__ == "__main__":
    main()

This ensures main() runs only when the script is executed directly, not when imported as a module.

Testing the Complete Program

Let's simulate a run with 3 rooms: a square (side 12), a rectangle (10x15), and another square (side 8). The expected output would be:

What is the number of rooms? 3
What is the shape of room 1? square
What is the side length of square room? 12
What is the shape of room 2? rectangle
What is the length of the room? 10
What is the width of the room? 15
What is the shape of room 3? square
What is the side length of square room? 8
The total square footage is 144 + 150 + 64 = 358

Your program should produce exactly this order of prompts. The lab's automated tests check prompt order, so ensure your prompt_user calls match the sequence: first main asks for number of rooms, then for each room: shape, then dimensions (once for square, twice for rectangle).

Common Pitfalls and Tips

  • Variable names: Use descriptive names like side, length, width, total. Avoid generic names like x or temp.
  • Type conversion: Always convert user input to the correct type before using it in calculations. The prompt_user function handles this, but double-check that it returns integers for dimensions.
  • Function length: Each function should be under 10 lines (not counting comments). If you find yourself writing more, you might be doing too much—refactor.
  • Testing incrementally: Test each function in the interactive shell before integrating. First test prompt_user, then room_square_feet, then main. This saves debugging time.

Connecting to Real-World Trends

This lab's concept of function composition is everywhere in modern tech. Consider how a smart home app like Google Home or Alexa composes functions: speech recognition (convert audio to text), intent parsing (what the user wants), and device control (turn on lights). Each is a separate function that gets composed to deliver a seamless experience. Or think of AI chatbots like ChatGPT: they break down a user's request into steps (understand query, retrieve knowledge, generate response) using composed functions under the hood.

In the world of finance, risk assessment tools use function composition: fetch market data, calculate volatility, apply model, output risk score. Even in gaming, a game like Fortnite composes functions for rendering graphics, handling player input, and updating game state. Learning to decompose problems into functions is a skill that transfers to any domain.

Conclusion

By completing this lab, you've practiced the core programming skill of functional decomposition. You've written three small, focused functions that work together to solve a larger problem. Remember to follow the rubric: include a header comment with author, date, and purpose; use descriptive variable names; and ensure each function has a docstring. Submit your squarefootage.py file via Canvas.

Functions are not just for assignments—they're how professional software is built. Next time you use a ride-sharing app or check the weather on your phone, think about the functions composing behind the scenes. Happy coding!