Functions in Python allow you to group code into reusable blocks that perform specific tasks. Learning how to define and call functions is essential to writing clean, efficient, and well-structured code.
This guide will explain how to define functions using the def
keyword, how to call them, and how parameters and return values work—with easy-to-understand examples.
1. Defining a Function
In Python, a function is defined using the def
keyword followed by the function name and parentheses. The code block inside the function is indented.
# Example 1: Defining a basic function
def greet():
print("Hello, welcome to Python programming!")
This defines a function named greet
that takes no parameters and prints a message.
2. Calling a Function
To execute the code inside a function, you "call" it using its name followed by parentheses.
# Example 2: Calling a function
greet() # Output: Hello, welcome to Python programming!
3. Function with Parameters
You can pass information into functions using parameters.
# Example 3: Function with one parameter
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Amit") # Output: Hello, Amit!
# Example 4: Function with two parameters
def add(a, b):
print("Sum is:", a + b)
add(5, 3) # Output: Sum is: 8
4. Returning Values from Functions
Functions can send data back using the return
keyword.
# Example 5: Function that returns a result
def multiply(x, y):
return x * y
result = multiply(4, 5)
print("Product:", result) # Output: Product: 20
5. Function with Default Parameters
You can assign default values to parameters. If no argument is provided during the call, the default value is used.
# Example 6: Default parameter
def welcome(name="Guest"):
print(f"Welcome, {name}!")
welcome() # Output: Welcome, Guest!
welcome("Priya") # Output: Welcome, Priya!
6. Function That Returns Multiple Values
You can return more than one value from a function as a tuple.
# Example 7: Returning multiple values
def get_min_max(numbers):
return min(numbers), max(numbers)
low, high = get_min_max([1, 3, 9, 2])
print(f"Lowest: {low}, Highest: {high}")
7. Calling Functions in Loops or Conditionals
# Example 8: Function used inside a loop
def is_even(n):
return n % 2 == 0
for i in range(1, 6):
if is_even(i):
print(f"{i} is even")
8. Function Naming Best Practices
- Use lowercase letters and underscores (e.g.,
calculate_total
). - Make names descriptive and meaningful.
- Avoid single-letter names except for short utility functions.
9. Summary
- Use
def
to define a function in Python. - Call a function using its name followed by parentheses.
- Use parameters to pass data and
return
to send results back. - Default parameters make functions flexible and reusable.
10. Final Thoughts
Defining and calling functions is a core concept in Python. It helps you organize your code logically and reuse it wherever needed. Once you're comfortable with this, you'll be able to build more scalable and maintainable programs with ease.