Lesson 4 - Functions
Lesson 4 - Functions
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a result.
Functions are units which perform a particular task, take some input, and which
may give some output. One of the most obvious advantages is the division of a program
into smaller parts.
SYNTAX:
Creating a Function
Calling a Function
Arguments
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
Example
If you try to call the function with 1 or 3 arguments, you will get an error:
If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
Example
Keyword arguments
You can also send arguments with the key = value syntax. This way the order of
the arguments does not matter.
The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.
**kwargs
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example:
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.
Recursive functions
Python also accepts function recursion, which means a defined function can
call itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a very
efficient and mathematically-elegant approach to programming.
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Recursion Example
String Functions
Python has a set of built-in methods that you can use on strings.
You can store them in data structures such as hash tables, lists, …
Functions as objects
In Python, a function can be assigned to a variable. This assignment does not call the
function, instead a reference to that function is created. Consider the below example,
for better understanding.
Example:
Example:
Returning function
As functions are objects, we can also return a function from another function. In
the below example, the create_adder function returns adder function.
Example:
Decorators
Syntax:
In the above code, gfg_decorator is a callable function, will add some code on
the top of some another callable function, hello_decorator function and return the
wrapper function.
Example:
Lambda
Syntax
Example
Example
Example
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:
Use that function definition to make a function that always doubles the number
you send in:
Or, use the same function definition to make a function that always triples the
number you send in:
Or, use the same function definition to make both functions, in the same
program:
Use lambda functions when an anonymous function is required for a short period
of time.
MODULES
As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you’ve written in several
programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is called a module;
definitions from a module can be imported into other modules or into the main module
To create a module just save the code you want in a file with the file extension
.py:
Use a Module
Now we can use the module we just created, by using the import statement:
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
Example
There is a built-in function to list all the function names (or variable names)
in a module. The dir() function:
Example
Note: The dir() function can be used on all modules, also the ones you
create yourself.
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Example
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
Example
Note: When importing using the from keyword, do not use the module name
when referring to elements in the module. Example: person1["age"], not
mymodule.person1["age"]
Packages
When developing a large application, you may end up with many different modules
that are difficult to manage. In such a case, you’ll benefit from grouping and organizing
your modules. That’s when packages come into play.
We can import specific modules from this package using the dot notation. For
example, to import the dataset module from the above package, we can use one of the
following code snippets:
There are a lot of built-in and open-source Python packages that you are probably
already using.
For example:
pandas is a Python package for fast and efficient processing of tabular data,
time series, matrix data, etc.
pytest provides a variety of modules to test new code, including small unit tests
or complex functional tests.
Package Manager
What makes Python a true power tool is the ecosystem of free and open source
libraries like Tensorflow, Netmiko, and Flask. These can be installed with a single
command using a package manager.
PyPI: The Package Index
PyPI packages allow developers to share and reuse code rather than having to
reinvent the wheel. As PyPI grew, the need for a package manager became so
apparent that Python eventually created its own standard package manager: pip.
Pip is built-in to Python, and can install packages from many different sources.
But PyPI.org is the primary and default package source used.
Pip is the “original” python package manager that others have attempted to
improve upon. Pipenv & Poetry are two package managers that have done this with
great success.
Pipenv is a package management tool that “aims to bring the best of all
packaging worlds” to Python. Pipenv is similar in spirit to Node.js’s npm and
Ruby’s bundler. It’s popular among the Python community because it merges virtual
environments and package management into a single tool. While pip is sufficient for
personal use, Pipenv is recommended for collaborative projects as it’s a higher-level
tool that simplifies dependency management for common use cases and can create
virtual environments.
Compared to Pip, the package selection is much smaller, but what Conda lacks
in quantity it makes up for in quality. Anyone can publish to PyPI, but only packages
curated by Anaconda are published in its repository. While Anaconda requires a paid
subscription, it grants access to thousands of curated packages and provides support
as well. Conda is an ideal package manager for those that are willing to pay to not worry
about license, quality, and vulnerability issues when dealing with third party/open-
source packages.
Library
Oftentimes, developers create Python libraries to share reusable code with the
community. To eliminate the need for writing code from scratch, they create a set of
useful functions related to the same area.
There are thousands of useful libraries available today. I’ll give just a few examples:
Beautiful Soup is a very popular Python library for getting data from the web.
The modules and packages inside this library help extract useful information from
HTML and XML files.
Requests is a part of a large collection of libraries designed to make Python
HTTP requests simpler. The library offers an intuitive JSON method that helps
you avoid manually adding query strings to your URLs.
missingno is very handy for handling missing data points. It provides informative
visualizations about the missing values in a dataframe, helping data scientists to
spot areas with missing data. It is just one of the many great Python libraries for
data cleaning.
Python Frameworks
Django is a Python framework for building web applications with less coding.
With all the necessary features included by default, developers can focus on their
applications rather than dealing with routine processes.
Flask is a web development framework that is known for its lightweight and
modular design. It has many out-of-the-box features and is easily adaptable to
specific requirements.
Bottle is another lightweight framework for web development that was originally
meant for building APIs. Its unique features are that it has no dependencies other
than the Python Standard Library and it implements everything in a single source
file.
https://learnpython.com/blog/python-modules-packages-libraries-frameworks/
https://blog.inedo.com/python-managing-python-packages
https://www.w3schools.com/python/python_functions.asp