It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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?

  1. Avoid repetition — write once, use many times.
  2. Organize code — make it easier to read and understand.
  3. Make code modular — break a complex program into smaller, manageable parts.
  4. 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 ().