Putting It Together
Think of your program like a kitchen station. The functions are specialised tools: one chops, one sautés, one plates.
main() is the chef who uses them in order. You do not want to chop onions every time someone looks at the knife; you only use it when preparing dinner.In real projects—like processing daily sales logs or generating report cards—the structure keeps logic testable and reusable. If your code is all jumbled together, changing one price calculation might break the receipt printer. Separation prevents that chaos.
The Bottom-Up Structure
def get_inventory():
return ["apples", "bananas"]
def display_items(items):
for item in items:
print(item)
def main():
stock = get_inventory()
display_items(stock)
if __name__ == '__main__':
main()Notice that
get_inventory only returns data and display_items only prints it, and neither does anything until main() calls it. Keeping each job in its own function makes them predictable: you can call get_inventory in a test without anything being printed.The Entry Point Guard
Python has a built-in variable named
__name__. When you run a file directly, Python sets it to '__main__'. If another script imports your module, __name__ becomes the module's name: the filename without .py. This distinction lets you control when code executes.def calculate_total(prices):
return sum(prices)
if __name__ == '__main__':
total = calculate_total([10, 20])
print(total) # Prints: 30
else:
pass # Nothing happens when importedelse: pass just shows the other case: real programs leave it out.Why This Matters
This pattern scales from a single-file script to a large application package. When your team grows, someone will import your utility functions into tests or other modules. The entry-point guard ensures they get clean, reusable tools—not a program that starts running in the background.
# utils.py
def filter_negatives(numbers):
return [n for n in numbers if n >= 0]
if __name__ == '__main__':
print(filter_negatives([1, -2, 3])) # [1, 3]In your upcoming exercises, you will complete
main() functions that call several helpers. Keep the pattern consistent: put each job in its own named function, then call them from a single entry point at the bottom of the file.