Ad space (banner)
🐍Python Lessons
Lesson 5 / 69

Writing Your First Function

This lesson covers how to define functions with def in Python, so you can write code that's reusable instead of repeated. It's written for anyone searching "how to write a Python function" or "Python def return".

In Python, you define a function with def, and use return to send a result back to the caller. Once you've named a piece of logic you use often, you can just call it by name whenever you need it. Like a recipe — once you've written down the steps and given them a name, you can reproduce the same result any time.

The sample code defines a function called greet, which takes a name argument and returns a greeting message with return. In Python, the body of a function is written as an indented block after the colon — and don't forget the colon at the end of the def line either.

A common beginner mistake is confusing return with print(). print() only displays something on screen and doesn't hand back a value, while return passes the function's result to the caller so it can be reused elsewhere. Misunderstanding this difference often leads to a function silently returning None.

In real development, the standard approach is to extract any calculation or processing you'll reuse into its own function. Breaking code into well-scoped functions makes it easier to read, and much easier to fix bugs and write tests for.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)