Introduction to Python functions
In all the previous chapters, you wrote Python code line by line to solve problems or process data. But what if you wanted to reuse that code? Or make your programs easier to read and maintain?
That’s where functions come in.
What Is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you can write a function once and call it wherever you need it.
Think of it like a recipe: you write it once and use it whenever you're hungry.
def greet():
print("Hello, welcome to Lance Py!")
This function is named greet
. You can run it (or call it) using:
greet()
Output
Hello, welcome to Lance Py!
Why Use Functions?
- Avoid repetition — write once, use many times.
- Organize code — make it easier to read and understand.
- Make code modular — break a complex program into smaller, manageable parts.
- Enable reuse — use your function across multiple projects or files.
Think Like a Developer
Every time you see repeated code or a clear task being done, ask:
"Can I turn this into a function?"
In the next lesson, we’ll see how to define and use functions properly, including passing values into them and returning results.
Key Takeaways
A function is a named block of code you can call whenever needed.
Functions help avoid repetition and make your code cleaner.
You use def
to define a function and call it using its name followed by parentheses ()
.