When writing programs, you’ll often need to repeat the same logic in multiple places. Instead of copying the same code again and again, you can use functions.
A function is a reusable block of code that performs a specific task.
📝 If You Want to Practice the Code
If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):
- From a Python prompt in your terminal or command line – see Getting Started with Python and Virtual Environment in Python and How to Set One Up
- Using Miniconda and Jupyter Notebook – see How to Install and Set Up Miniconda and Install Jupytor Notebook Windows, How to Install and Set Up Miniconda on MacOS, How to Install and Set Up Miniconda on Linux (Ubuntu), and Getting Started with Jupyter Notebooks.
- On Google Colab (browser-based, no installation required) – see Getting Started with Google Colab.
- Through VS Code – see Setting Up VS Code for Python Development.
👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.
🔹 Defining a Function
You define a function using the def keyword:
def greet():
print("Hello, welcome to Python!")
Now you can call it anywhere:
greet()
👉 Output: Hello, welcome to Python!
🔹 Functions with Parameters
Functions can take inputs called parameters.
def greet_user(name):
print("Hello,", name)
Calling the function with an argument:
greet_user("Alice")
👉 Output: Hello, Alice
🔹 Functions that Return Values
Sometimes you want a function to give back a result using return.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
👉 Output: 8
Without return, a function just prints but doesn’t store the value.
🔹 Default Parameters
You can provide default values for parameters.
def greet_user(name="Guest"):
print("Hello,", name)
greet_user()
greet_user("Bob")
👉 Output:
Hello, Guest
Hello, Bob
🔹 Multiple Return Values
A function can return more than one value as a tuple.
def calculate(a, b):
return a + b, a - b
sum_val, diff_val = calculate(10, 4)
print("Sum:", sum_val)
print("Difference:", diff_val)
👉 Output:
Sum: 14
Difference: 6
📝 Mini Task
Try writing these simple functions yourself:
- A function
square(n)that returns the square of a number. - A function
is_even(n)that returnsTrueif the number is even, otherwiseFalse. - A function
greet_full(first, last)that prints"Hello, First Last!".
Example:
def is_even(n):
return n % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
✅ Summary
- Functions help organize and reuse code.
- Use
defto define andreturnto send back values. - Parameters let you pass input into functions.
- Default values make parameters optional.
- Functions can even return multiple values.
By mastering functions, your Python programs will become cleaner, shorter, and easier to understand.