What Functions Are For
In this tutorial, we'll understand why functions help you organise and reuse code.
A function is a reusable block of code with a name.
You have already used built-in functions:
print("Hello")
len("Python")
int("42")
These functions already exist in Python. You can also create your own.
Why Functions Help
Functions help when code starts repeating.
Without a function:
print("Welcome, Ada")
print("Remember to check your tasks")
print("Welcome, Grace")
print("Remember to check your tasks")
With a function:
def welcome_user(name):
print("Welcome,", name)
print("Remember to check your tasks")
welcome_user("Ada")
welcome_user("Grace")
Now the greeting logic lives in one place. If the message changes, you edit the function once.
Functions Make Code Easier to Read
Good function names explain what a piece of code does:
def calculate_total(price, quantity):
return price * quantity
Even before reading the inside, you can guess the purpose.
Functions Can Hide Detail
You do not need to know how len() works inside to use it:
print(len(["a", "b", "c"]))
Your own functions can work the same way. They let the rest of your program say what it wants done without repeating every detail.
When to Create a Function
Create a function when:
- You repeat the same code
- A block of code has a clear job
- You want to make your program easier to read
- You want to test one small part of your program
Do not turn every single line into a function. A function should have a useful purpose.
Practice
Find two repeated print statements in a small program and turn them into a function.