Pulsars
0 %
Log inSign up

Breaking Your Code into Functions

Why Use Functions

Why break your code into functions?

As a program grows, it quickly becomes hard to read if everything is written in sequence, without structure. A function is a named block of code that you write once and can then reuse as many times as you want, simply by calling it by name.

Get in the habit of asking yourself this question: am I going to redo this calculation, this check, this display several times in my program? If so, it's time to turn it into a function.

Functions bring two major benefits:

  • reusability: you write the logic once, then call it wherever you need it, without copying the code again,
  • readability: a program broken into well-named functions reads almost like a sequence of steps in plain English (calculate_average, display_result...), which makes it easier to understand and fix.

There is a third benefit, just as important: if you need to fix a bug or improve a calculation, you only have to do it in one place (inside the function), instead of having to track down every copy of the same code scattered throughout the program.

You're already using functions without necessarily knowing it: print(...) and input(...) are functions provided by Python. In this course, you'll learn to create your own.