Python Functions - Jupyter Notebook_429d14e844f4cef21a8fc9ac70ba92d9
Python Functions - Jupyter Notebook_429d14e844f4cef21a8fc9ac70ba92d9
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
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.
Code Reusability: The same code can be run multiple times without repeating it.
Modularity: Functions break long programs into smaller, more manageable parts.
Let’s begin with a simple example. The add_three() function below accepts a number, adds
three to it, and returns the result.
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.
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.
13
Explanation:
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:
Example:
Accessing Docstrings:
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.
In [5]: print(greet.__doc__)
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
Hello, World!
Passing Arguments to Functions
You can pass one or more arguments to a function.
Hello, John
John is a Programmer
24
10 Hello 3.25
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 Python, functions can have default values for arguments. If no value is provided when calling
the function, the default value is used.
Example:
In a function definition, parameters with default values should be defined after parameters
without default values.
When calling a function, positional arguments should always appear before keyword
arguments.
Jessa 12 Six
3. Order of keyword arguments doesn't matter, but they must match the parameter names
in the function:
Jessa 12 Six
---------------------------------------------------------------------------
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')
Example:
Average = 63.333333333333336
Note: args is just a name. You can use any name, like *subjects .
Example:
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.
74
min()
The min() function returns the item with the lowest value in an iterable.
61
len()
The len() function returns the number of items in an object (such as a list or string).
sum()
The sum() function returns the total of all items in an iterable.
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.
zip()
The zip() function combines two or more iterables (like lists) and returns a list of tuples.