Functions in Python
In this lesson, you will learn how to organize your code with functions. A function is a reusable
block of code designed to perform a specific task. Functions allow you to write code once and
use it multiple times without duplicating it. This makes your programs more efficient, modular,
and easier to maintain.
Types of Functions
There are two types of functions in Python:
1. Built-in functions: Predefined functions in Python that are readily available for use.
Examples include print() , len() , sum() , etc.
2. User defined functions: Functions that are created by the user to perform specific tasks.
Why Use Functions?
Functions offer several benefits:
Code Reusability: The same code can be run multiple times without repeating it.
Modularity: Functions break long programs into smaller, more manageable parts.
Collaboration: Functions can be shared and reused by other programmers.
Defining a Function: A Simple Example
Let’s begin with a simple example. The add_three() function below accepts a number, adds
three to it, and returns the result.
In [1]: # Define the function
def add_three(input_var):
output_var = input_var + 3
return output_var
Function Components
Every function in Python consists of two main parts: header and body.
1. Function Header
The function header defines the name of the function and its argument(s).
Every function header starts with the keyword def , indicating that a function is being
defined.
Function name: In the example, the name of the function is add_three .
Argument(s): The variable input_var is an argument. Arguments represent the input(s)
passed to the function. They are enclosed in parentheses right after the function name.
The header ends with a colon : .
2. Function Body
The function body contains the code that performs the function's task.
Every line in the function body must be indented by four spaces (or one tab).
The body processes the input argument input_var and returns the result using a
return statement.
Calling a Function
To execute or "call" a function, use its name followed by parentheses, passing any required
arguments.
In [2]: # Run the function with 10 as input
new_number = add_three(10)
# Check that the value is 13
print(new_number)
13
Explanation:
1. The function add_three(10) is called with 10 as the argument.
2. Inside the function:
input_var = 10
output_var = 10 + 3 = 13
3. The result 13 is returned and stored in the variable new_number , which is printed as
expected.
Naming Functions
When naming functions, follow these guidelines:
Use lowercase letters.
Separate words with underscores (e.g., add_three ).
Choose descriptive names to clearly indicate the function's purpose.
Docstrings in Python Functions
A docstring is a special string placed as the first statement in a function definition. It is used to
describe the purpose of the function, its parameters, return values, and other details.
Example:
In [3]: def greet(name):
"""
This function greets the person passed as a parameter.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
"""
return "Hello, " + name + "!"
Accessing Docstrings:
Use help() to display a function's docstring:
In [4]: help(greet)
Help on function greet in module __main__:
greet(name)
This function greets the person passed as a parameter.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
Or access the docstring directly:
In [5]: print(greet.__doc__)
This function greets the person passed as a parameter.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
Functions Without a return Statement
A function in Python can be defined without a return statement. In this case, the function
automatically returns None .
In [6]: # Define a function without return
def hello():
print('Hello, World!')
# Call the function
hello() # Output: Hello, World!
Hello, World!
Passing Arguments to Functions
You can pass one or more arguments to a function.
Example 1: Single Argument
In [7]: def hello(name):
print('Hello,', name)
hello('John') # Output: Hello, John
Hello, John
Example 2: Multiple Arguments
In [8]: def describe_person(name, job):
print(name, 'is a', job)
describe_person('John', 'Programmer') # Output: John is a Programmer
John is a Programmer
Return Values in Functions
You can use the return statement to send back the result of a function.
Example: Multiply Two Numbers
In [9]: def multiply(a, b):
return a * b
result = multiply(12, 2)
print(result) # Output: 24
24
Example: Returning Multiple Values
A function can return multiple values, separated by commas.
In [10]: def get_values():
value1 = 10
value2 = "Hello"
value3 = 3.25
return value1, value2, value3
result1, result2, result3 = get_values()
print(result1, result2, result3)
10 Hello 3.25
Functions with Different Data Types
Functions can work with different data types, even mixing them.
Example: Multiplying a String
In [11]: # Multiply a string with an integer
print(multiply(2, "Michael Jackson ")) # Output: Michael Jackson Michael Jack
Michael Jackson Michael Jackson
Types of Arguments in Python
Python supports multiple types of arguments in the function definition. Here is the complete list:
Positional Arguments
Keyword Arguments
Default Arguments
Variable Length Positional Arguments ( *args )
Variable Length Keyword Arguments ( **kwargs )
How to Pass Keyword Arguments to a Function
In Python, functions can accept keyword arguments. This allows you to specify parameters in
any order because the Python interpreter uses the provided keywords to match the values to
the correct parameters.
Example:
In [12]: # Function with two parameters
def student(name, age):
print('Student Details:', name, age)
# Call function with positional arguments
student('Jessa', 14)
# Call function with keyword arguments
student(name='Jon', age=12)
# Call function with a mix of positional and keyword arguments
student('Donald', age=13)
Student Details: Jessa 14
Student Details: Jon 12
Student Details: Donald 13
How to Pass Default Arguments to a Function
In Python, functions can have default values for arguments. If no value is provided when calling
the function, the default value is used.
Example:
In [13]: # Function with default arguments for 'grade' and 'school'
def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)
# Without passing grade and school
student('Jon', 12)
# Passing a new value for grade
student('Kelly', 12, 'Six')
# Passing all arguments
student('Jessa', 12, 'Seven', 'XYZ School')
Student Details: Jon 12 Five ABC School
Student Details: Kelly 12 Six ABC School
Student Details: Jessa 12 Seven XYZ School
Important points to remember about function arguments
1. Default arguments must follow non-default arguments:
In a function definition, parameters with default values should be defined after parameters
without default values.
In [14]: # Incorrect: default argument 'grade' before non-default argument 'age'
def get_student(name, grade='Five', age):
print(name, age, grade)
Cell In[14], line 2
def get_student(name, grade='Five', age):
^
SyntaxError: non-default argument follows default argument
In [15]: # Correct: non-default argument 'age' comes before default argument 'grade'
def get_student(name, age, grade='Five'):
print(name, age, grade)
2. Positional arguments must come before keyword arguments:
When calling a function, positional arguments should always appear before keyword
arguments.
In [16]: # Incorrect: positional argument after keyword argument
get_student(name='Jessa', 12, 'Six')
Cell In[16], line 2
get_student(name='Jessa', 12, 'Six')
^
SyntaxError: positional argument follows keyword argument
In [17]: # Correct: positional arguments first, followed by keyword arguments
get_student('Jessa', 12, grade='Six')
Jessa 12 Six
3. Order of keyword arguments doesn't matter, but they must match the parameter names
in the function:
In [18]: # Correct: keyword arguments in any order
get_student(grade='Six', name='Jessa', age=12)
Jessa 12 Six
In [19]: # Incorrect: passing an invalid keyword argument 'standard'
get_student(name='Jessa', age=12, standard='Six')
# TypeError: get_student() got an unexpected keyword argument 'standard'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[19], line 2
1 # Incorrect: passing an invalid keyword argument 'standard'
----> 2 get_student(name='Jessa', age=12, standard='Six')
TypeError: get_student() got an unexpected keyword argument 'standard'
How to Pass Variable Length Positional Arguments to a Function
( *args )
Variable-length arguments allow you to pass any number of positional arguments to a function.
The function collects these arguments into a tuple, which you can iterate over.
Example:
In [20]: # Function with variable-length positional arguments
def percentage(*args):
total = sum(args)
avg = total / len(args)
print('Average =', avg)
percentage(56, 61, 73)
Average = 63.333333333333336
Note: args is just a name. You can use any name, like *subjects .
How to Pass Variable Length Keyword Arguments to a Function
( **kwargs )
The **kwargs syntax allows you to pass an arbitrary number of keyword arguments to a
function. These arguments are collected into a dictionary, which you can then access using
key-value pairs.
Example:
In [21]: # Function with variable-length keyword arguments
def percentage(**kwargs):
for subject, marks in kwargs.items():
print(subject, "=", marks)
# Pass multiple keyword arguments
percentage(math=56, english=61, science=73)
math = 56
english = 61
science = 73
Built-In Functions in Python
Python comes with many built-in functions that can help perform specific tasks. Let's look at
some of the most common ones:
max()
The max() function returns the item with the highest value, or the highest value in an iterable.
In [22]: marks = [65, 71, 68, 74, 61]
print(max(marks)) # Output: 74
74
min()
The min() function returns the item with the lowest value in an iterable.
In [23]: print(min(marks)) # Output: 61
61
len()
The len() function returns the number of items in an object (such as a list or string).
In [24]: print(len(marks)) # Output: 5
sum()
The sum() function returns the total of all items in an iterable.
In [25]: total_marks = sum(marks)
print(total_marks) # Output: 339
339
round()
The round() function returns a number rounded to a specified number of decimal places.
In [26]: print(round(10.0456, 2)) # Output: 10.05
10.05
pow()
The pow() function returns the value of one number raised to the power of another.
In [27]: print(pow(3, 2)) # Output: 9
zip()
The zip() function combines two or more iterables (like lists) and returns a list of tuples.
In [28]: languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]
result = zip(languages, versions)
print(list(result)) # Output: [('Java', 14), ('Python', 3), ('JavaScript', 6)
[('Java', 14), ('Python', 3), ('JavaScript', 6)]