Python - Functions and Libraries
Python - Functions and Libraries
❏ Functions provides better modularity for your application and a high degree
of code reusing.
❏ As you already know, Python gives you many built-in functions like print()
etc. but you can also create your own functions.
➢ Code reusability: Functions allow you to reuse code by defining a block of code
that can be called multiple times from within your program. This reduces the
amount of code you need to write and makes your code more modular and
maintainable.
➢ Call the function: To call the function, simply type the function
name followed by parentheses and any required arguments.
Python Functions: Calling
❖ In Python, a function can take zero or more parameters. When a function is called, the values
passed to the function are referred to as arguments.
❖ There are two types of function parameters in Python: positional parameters and keyword
parameters.
❖ In addition to these two types of parameters, Python also allows for default parameter values.
Default values are specified in the function header and are used if no value is passed for that
parameter when the function is called.
Functions Parameters: Positional Parameters
❖ In Python, positional parameters are function parameters that are passed to the function in
the order they are defined in the function header. When you call a function with positional
parameters, the values are assigned to the parameters in the order they appear in the
function definition.
❖ In this function, x and y are positional parameters. When you call the add() function, you
need to pass two arguments in the order they appear in the function definition
Functions Parameters: Positional Parameters
❖ The number of arguments must match the number of parameters: When calling a
function with positional parameters, the number of arguments passed to the
function must match the number of parameters defined in the function header. If
you pass too many or too few arguments, you will get a TypeError.
❖ Positional parameters can have default values: You can also give a positional
parameter a default value. If the parameter is not passed when calling the function,
the default value will be used instead. For example:
Functions Parameters: Positional Parameters
➢ In this function, name and message are keyword parameters. When you call the greet()
function with keyword parameters, you specify the parameter name followed by the
corresponding argument value, separated by an equal sign:
Functions Parameters: Keyword Parameters
❖ To call the function, we use the following format:
❖ Anonymous functions are also known as lambda functions because they are
defined using the lambda keyword.
❖ Lambda functions are useful for writing small, one-time-use functions that do not
need to be named or defined separately.
❖ They are particularly useful when you need to pass a function as an argument to
another function. Instead of defining a separate function, you can define a lambda
function on the fly and pass it directly to the other function.
Anonymous Functions
❖ You can call a lambda function just like any other function:
❖ Lambda functions can also be used with built-in functions like map()
and filter(). For example, the following code uses a lambda function
with map() to square each element in a list:
Anonymous Functions: Properties
❖ Lambda functions can take any number of arguments: Lambda functions can take
any number of arguments, including zero arguments. The syntax for a lambda
function with zero arguments is simply lambda: expression.
❖ Lambda functions can have default values: You can give a lambda function
default values for its arguments just like you would with a regular function.
❖ It's important to note that recursive functions can be memory-intensive, particularly if the recursion depth is
very deep. Python has a maximum recursion depth of 3000 by default, so if your program requires deeper
recursion, you may need to increase this limit using the sys.setrecursionlimit() function.
Recursion
❖ Recursion can be used to solve many types of problems: Recursion can be used to solve a wide
variety of problems, including searching, sorting, and tree traversal. Recursive algorithms can
be elegant and easy to understand, but they can also be less efficient than iterative algorithms
for some types of problems.
❖ Recursion requires a base case: A base case is the condition that causes the recursion to stop.
Without a base case, the recursion will continue indefinitely, eventually causing a stack
overflow error. In the factorial() example, the base case is n=0.
❖ Recursion involves a function calling itself: In a recursive function, the function calls itself
with a smaller or simpler version of the input. In the factorial() example, the function calls
itself with the argument n-1.
Nested Functions
❖ In Python, it's possible to define functions inside other functions. These are called nested
functions or inner functions.
❖ Nested functions are useful for creating helper functions that are only used within a larger
function, and for creating closures, which are functions that can access variables in their parent
function's scope.
Nested Functions
❖ Nested functions can also be used to create closures. A closure is a function that "remembers"
the values of variables in its parent function's scope, even after the parent function has returned.
Here's an example of a closure:
Nested Functions: Decorators
❖ Nested functions can access variables from their parent function's scope.
❖ A decorator function is a function that takes another function as an argument and returns a new
function that adds some additional functionality to the original function.
Nested Functions: Factory Functions
❖ Nested functions can be used to create factory functions: A factory function is a function that
returns another function. Factory functions can be created using nested functions. Here's an
example:
Python Libraries: Standard Libraries
❖ Python comes with a variety of standard libraries that are included with the language. These
libraries provide a wide range of functionality, from working with files and directories, to
networking, to cryptography, and much more.
Python Libraries: os
❖ The os library in Python provides a way to interact with the operating system, such as creating
and removing directories, listing directory contents, and getting information about files. Here
are some commonly used functions in the os library:
❖ The sys module in Python provides access to some variables used or maintained by the
interpreter, as well as functions that interact with the Python runtime environment. Here are
some commonly used functions and variables in the sys module:
➢ sys.argv: A list of command line arguments passed to the Python script. sys.argv[0] is
usually the name of the script itself.
➢ sys.exit([arg]): Exits the Python interpreter with an optional exit status arg. If arg is
omitted, the exit status is zero.
➢ sys.platform: A string identifying the operating system platform that Python is running on,
such as "win32", "linux", or "darwin".
➢ sys.version: A string containing the version number and build information of the Python
interpreter.
Python Libraries: sys
❖ The math module in Python provides a collection of mathematical functions that operate on
numerical data. Here are some commonly used functions in the math module:
❖ The random module in Python provides functions for generating random numbers and
sequences. Here are some commonly used functions in the random module:
❖ The re module in Python provides support for regular expressions, which are a powerful and
flexible way to search for and manipulate text. Here are some commonly used functions in the
re module:
➢ re.search(pattern, string[, flags]): Searches for the first occurrence of pattern in string, and
returns a match object if found. flags can be used to modify the behavior of the search.
➢ re.match(pattern, string[, flags]): Searches for pattern at the beginning of string, and
returns a match object if found. flags can be used to modify the behavior of the search.
➢ re.findall(pattern, string[, flags]): Searches for all non-overlapping occurrences of pattern
in string, and returns a list of matching strings.
Python Libraries: re
❖ The json module in Python provides functions for encoding and decoding JSON (JavaScript
Object Notation) data. JSON is a lightweight data interchange format that is easy for humans to
read and write, and easy for machines to parse and generate. Here are some commonly used
functions in the json module:
❖ JSON is a lightweight and easy-to-read data interchange format that is widely supported by many
programming languages, making it a popular choice for data exchange between different systems and
applications.
❖ JSON can represent complex data structures, including arrays, objects, and nested data, making it a
flexible and powerful format for data storage and exchange.
❖ JSON is human-readable and easy to parse, making it useful for debugging and troubleshooting data
exchange issues.
❖ JSON is often used in web development, where it is a popular format for REST APIs (Application
Programming Interfaces) and AJAX (Asynchronous JavaScript and XML) requests. JSON data can be
easily parsed and manipulated using JavaScript, making it a natural fit for web development.
Python Libraries: json
❖ The csv module in Python provides functions for working with CSV (Comma-Separated
Values) files, which are a common file format for storing and exchanging tabular data. Here are
some commonly used functions in the csv module:
❖ The datetime module in Python provides classes and functions for working with dates and
times. Here are some commonly used classes and functions in the datetime module:
➢ date: Represents a date (year, month, day) and provides methods for manipulating and
formatting dates.
➢ time: Represents a time (hour, minute, second, microsecond) and provides methods for
manipulating and formatting times.
➢ datetime: Represents a date and time and provides methods for manipulating and
formatting dates and times.
➢ timedelta: Represents a duration or difference between two dates or times, and provides
methods for performing arithmetic with durations.
Python Libraries: datetime
➢ pyplot: Provides a simple interface for creating and customizing plots and charts.
➢ figure: Creates a new figure for a plot or chart.
➢ subplot: Creates a new subplot within a figure.
➢ plot: Creates a line plot or scatter plot.
➢ scatter: Creates a scatter plot.
➢ bar: Creates a bar chart.
➢ hist: Creates a histogram.
➢ boxplot: Creates a box plot.
➢ set_xlabel/set_ylabel: Sets the labels for the x-axis and y-axis.
External Libraries: matplotlib
➢ Dataset loading utilities: Provides functions for loading and working with popular datasets, such as the
Iris dataset and the MNIST dataset.
➢ Preprocessing: Provides functions for preprocessing data, such as scaling, normalization, and feature
selection.
➢ Supervised learning algorithms: Provides a wide range of algorithms for supervised learning, such as
linear regression, logistic regression, decision trees, random forests, and neural networks.
➢ Unsupervised learning algorithms: Provides a wide range of algorithms for unsupervised learning,
such as k-means clustering, hierarchical clustering, and principal component analysis (PCA).
External Libraries: Tensorflow
❖ TensorFlow is an open-source machine learning library developed by Google. It is designed to build and
train machine learning models for a wide range of applications, including image and speech recognition,
natural language processing, and reinforcement learning. TensorFlow provides a powerful and flexible
platform for building and deploying machine learning models, with support for both low-level operations
and high-level abstractions.
➢ Computation graphs: TensorFlow uses computation graphs to represent machine learning models as a
series of mathematical operations. This allows for efficient computation on both CPUs and GPUs, and
makes it easy to optimize and parallelize the model.
➢ Automatic differentiation: TensorFlow provides an automatic differentiation feature, which allows for
efficient computation of gradients for backpropagation-based optimization algorithms.
➢ High-level APIs: TensorFlow provides high-level APIs (such as Keras and Estimators) for building
and training machine learning models, which can simplify the model-building process for beginners.
External Libraries: Keras
❖ Keras is a high-level neural network API written in Python that runs on top of TensorFlow (as well as other
backends such as Theano and Microsoft Cognitive Toolkit). It was developed with a focus on enabling fast
experimentation with deep neural networks, with the goal of making it easy to go from idea to result as smoothly
as possible.
➢ Modular design: Keras provides a modular design that allows users to easily mix and match different layers
and activation functions to create custom neural network architectures.
➢ Built-in layers and activation functions: Keras provides a range of built-in layers and activation functions
for building custom models, including convolutional layers, recurrent layers, and fully connected layers.
➢ Customizable loss functions and metrics: Keras allows users to define custom loss functions and metrics
for training and evaluating their models.
➢ Preprocessing and data augmentation: Keras provides a range of utilities for preprocessing and augmenting
data, including image preprocessing and sequence padding.
➢ Model saving and loading: Keras provides utilities for saving and loading trained models, which can be
useful for deploying models in production environments.
External Libraries: Pytorch
❖ PyTorch is an open-source machine learning library developed by Facebook. It provides a flexible and
efficient platform for building and training machine learning models, with support for both CPU and GPU
computation. PyTorch is known for its dynamic computational graph, which allows for more flexible and
efficient computation compared to static computational graphs used in other libraries like TensorFlow.
➢ Dynamic computational graph: PyTorch uses a dynamic computational graph to represent machine
learning models as a series of mathematical operations. This allows for more flexible and efficient
computation compared to static computational graphs used in other libraries like TensorFlow.
➢ Automatic differentiation: PyTorch provides an automatic differentiation feature, which allows for
efficient computation of gradients for backpropagation-based optimization algorithms.
➢ GPU acceleration: PyTorch provides support for GPU acceleration, which can greatly accelerate the
training of large-scale models.
External Libraries: OpenAI Gym
❖ OpenAI Gym is an open-source toolkit for developing and comparing reinforcement learning algorithms. It
provides a wide range of environments for training and testing reinforcement learning agents, including
classic control problems, Atari games, and robotics simulations. OpenAI Gym is designed to be easy to use,
with a simple and consistent interface that allows for rapid experimentation and prototyping.
➢ A wide range of environments: OpenAI Gym provides a wide range of environments for training and
testing reinforcement learning agents, including classic control problems, Atari games, and robotics
simulations.
➢ Customizable environments: OpenAI Gym allows users to create their own custom environments,
which can be used to test and train reinforcement learning agents on specific tasks.
➢ Integration with other machine learning libraries: OpenAI Gym integrates with other popular machine
learning libraries, such as TensorFlow and PyTorch, which allows for seamless integration with other
machine learning workflows.
Activity I (2 hrs)
❏ Write and run every example code we covered up till now in the training.
❏ Run the pre-existing more complicated code on the website and examine those codes
to better understand them (Classify IMDB movie reviews as either positive or
negative.)
Thank You!