When writing functions in Python, two key concepts help make your code flexible and powerful: parameters and return values. Understanding these will allow you to write functions that accept input, process it, and give back useful results.
Parameters are variables listed inside the parentheses in a function definition. They act as placeholders for the values (called arguments) that you pass when calling the function.
def greet(name):
return f"Hello, {name}!"
Here, name is a parameter. When you call greet("Wahab"), "Wahab" is the argument passed to the name parameter.
Python supports several types of parameters:
Positional Parameters
Defined in order and must be passed in the same order.
def add(a, b):
return a + b
Default Parameters
Provide default values if no argument is passed.
def greet(name="Guest"):
return f"Hello, {name}!"
Keyword Arguments
Specify arguments by name during the function call.
greet(name="Wahab")
Variable-Length Arguments
*args for multiple positional arguments
**kwargs for multiple keyword arguments
def print_all(*args):
for item in args:
print(item)
A return value is the output that a function sends back to the caller using the return keyword.
def square(n):
return n ** 2
Calling square(4) returns 16.
If you don’t use return, the function returns None by default.
To pass results back to the caller
To chain function calls
To store results in variables
To make functions testable and reusable
def get_full_name(first, last):
return f"{first} {last}"
full_name = get_full_name("Abdul", "Wahab")
print(full_name) # Output: Abdul Wahab
Use descriptive parameter names
Keep functions focused on one task
Always return meaningful values
Avoid modifying global variables inside functions
Write a function is_positive(n) that returns True if n is positive, otherwise False.
def is_positive(n):
return n > 0
Mastering parameters and return values is essential for writing clean, modular, and reusable Python code. As you move into data science and machine learning, these concepts will help you build smarter functions and scalable projects.
Next Up: Scope and lifetime of variables