Chapter 10 ยท Reusing Code
Functions
As programs grow, you find yourself writing the same thing again and again. Functions let you write a block once, give it a name, and reuse it forever - the foundation of all real software.
A function is a recipe. You write it down once ("how to make bread"), give it a name, and from then on you just say "make bread" instead of listing every step again. You can even hand it different ingredients each time.
Writing your own function
Use def, a name, brackets, and a colon. The indented block is the function's body:
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()
Defining a function doesn't run it โ greet() is what actually runs it. Here we called it
twice without repeating the code.
Giving a function information (parameters)
Values in the brackets let a function work on different data each time:
def greet(name):
print(f"Hello, {name}!")
greet("Grace")
greet("Godfrey")
Getting an answer back (return)
Functions can hand back a result with return, which you can store and use:
def add(a, b):
return a + b
total = add(10, 5)
print(total)
print(add(100, 250))
The difference: print just shows something; return gives a value back to the
program so you can keep working with it.
Putting it all together
def area_of_room(length, width):
return length * width
rooms = [(4, 3), (5, 5), (2, 6)]
for length, width in rooms:
print(f"A {length}x{width} room is {area_of_room(length, width)} square metres")
Write a function double(n) that returns a number times two. Call it with a few different
numbers and print the results.
๐ You've reached the end of the beginner course
Look how far you've come. You can now store data, make decisions, repeat work, hold collections, and package logic into reusable functions โ that's the real core of programming, and it's the same in every language you'll ever learn.
What next? Keep the playground open and build small things: a tip calculator, a quiz, a to-do list. Building beats reading every time. When you're ready for the web, our PHP OOP course takes these same ideas into real websites with databases and login.
Recap
def name(parameters):defines a reusable block.- Parameters feed it different data;
returnhands a result back. - Functions keep programs short, clear and free of repetition โ the habit of every good developer.