0% found this document useful (0 votes)
31 views

Report 5

This document is an industrial training report submitted by Jyoti to fulfill requirements for a Bachelor of Technology degree in Computer Science and Engineering. It provides an overview and summary of a training project on Python programming conducted under the guidance of Dr. Vinod Todwal. The report documents Jyoti's work in learning Python including its history, concepts, popularity, and use in object oriented programming. It also includes chapters covering Python setup, core concepts, working with libraries, and conclusions.

Uploaded by

p.jyotii0008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Report 5

This document is an industrial training report submitted by Jyoti to fulfill requirements for a Bachelor of Technology degree in Computer Science and Engineering. It provides an overview and summary of a training project on Python programming conducted under the guidance of Dr. Vinod Todwal. The report documents Jyoti's work in learning Python including its history, concepts, popularity, and use in object oriented programming. It also includes chapters covering Python setup, core concepts, working with libraries, and conclusions.

Uploaded by

p.jyotii0008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

A

Industrial Training Report


On
PYTHON PROGRAMMING
Submitted
In partial fulfillment
For the award of the Degree of
Bachelor of Technology
in Department of Computer Science and Engineering

Submitted To Submitted By
Dr. Subhash Chandra Jyoti

HOD, CSE 20ERWCS025

Department of Computer Science and Engineering


Rajasthan College of Engineering for Women
Rajasthan Technical University
Session 2023-2024
i
Candidate’s Declaration
I hereby declare that the work, which is being presented in the Industrial Training/Seminar Report, entitled
“PYTHON PROGRAMMING” in partial fulfillment for the award of Degree of “Bachelor’s of Technology”
in Department of Computer Science and Engineering and submitted to the Department of Computer Science
& Engineering, Rajasthan College Of Engineering For Women, Rajasthan Technical University is a record of
my own investigations carried under the Guidance of Mr. Vinod Todwal, Department of Computer Science &
Engineering, RCEW.

I have not submitted the matter presented in this report anywhere for the award of any other Degree.

Jyoti

20ERWCS025

Rajasthan College of Engineering for Women, Jaipur

Counter Signed by

Mr. Vinod Todwal

Assistant Professor

Department of Computer Science and Engineering

ii
Certificate

This is to certify that the Industrial Training/Seminar report entitled “Python Programming” done by Ms
JYOTI Enrollment no. 20ERWCS025 is an authentic work carried out by her at Rajasthan College of
Engineering for Women under my guidance. The matter embodied in this Industrial Training work has not been
submitted earlier for the award of any degree or diploma to the best of my knowledge and belief.

Mr. Vinod Todwal

Assistant Professor

Rajasthan College of Engineering for Women, Jaipur

Rajasthan Technical University

iii
TABLE OF CONTENTS

Certificate i
Declaration ii
Acknowledgement iii
Abstract iv
List of Figures v-vi
List of Tables vii
Table of Content viii- x

Chapter 1 Introduction 1
1.1. Introduction of python programming 1
1.2. History 1
1.3. Key Concepts 2
1.4. Popularity 3
1.5. Importance 4
1.6. Object Oriented Programming 6
Chapter 2 Python setup 7
2.1. Commandline Basics 7
2.2. Installing python 8
2.3. Running python code 9
Chapter 3 Concept of Python 10
3.1. Variables 11
3.2. Datatypes 12
3.3. List 13
3.4. Tuple 14
3.5. Difference between list and tuples 15
3.6. Dictionaries 16
3.7. Operators in python 17
3.8. Control structure 18
3.9. Functions 19
Chapter 4 Working with Libraries 20
4.1. Basic libraries 21
iv
4.2. Working of libraries 22
4.3. Uses of libraries 23
4.2. Web scrapping in python 24
4.3. Working with images in python 25
4.4. Working with pdf files in python 26
4.5. Graphical user interface 29
4.6. Scope of python 30
4.7. Application of python 31
Chapter 5 Conclusion and Future Work 32
5.1. Summary and Contributions
5.2. Future Scope
Reference 41

v
LIST OF TABLES

S. No. Table No. Title Page No.

1 Table 3.4 Difference between list and tuple 4

2 Table 2.1 Operators 14

vi
LIST OF FIGURES

S.No. Figure No. Title Page No.

1 Figure 1.1 Concept of Python 3

2 Figure 2.1 Verifying the Installation 5

3 Figure 3.1 Creating a List 18

4 Figure 3.2 Accessing the Elements 19

5 Figure 3.3 Slicing 20

6 Figure 3.4 Modifying Elements 21

7 Figure 3.5 Adding Elements 22

8 Figure 3.6 Removing Elements 23

9 Figure 3.7 Finding Elements 23

10 Figure 3.8 Length of a List 34

11 Figure 3.9 List Methods 18

12 Figure 3.10 Nested Lists 22

13 Figure 3.11 List Comprehensives 22

14 Figure 3.12 Creating a Tuple 22

15 Figure 3.13 Arithmetic Operators 22

16 Figure 3.14 Comparison Operators 22

17 Figure 3.15 Logical Operators 22

18 Figure 3.16 Assignment Operators 22

19 Figure 3.17 Bitwise Operators 22

20 Figure 3.18 Identity Operator 22

21 Figure 3.19 For Loops 22

22 Figure 3.20 While Loops 22

23 Figure 3.21 Function 22

24 Figure 4.1 Install PyPDF2 2

25 Figure 4.2 Reading PDF Files 22


26 Figure 4.3 Merging PDF Files 22
vii
27 Figure 4.4 Creating PDF Files 22

28 Figure 4.5 Application of Python Programming 22

viii
Acknowledgement

I would like to thank the Assistant Professor, Computer Science and Engineering Mr. Vinod Todwal for his
valuable guidance. I appreciate his presence for giving all discussions, suggestions and the time for me
whenever I needed him. He consciously or unconsciously leveraged his key and creative insights wherever
applicable in the project. Amidst of him busy schedule, he made himself available for any query related to
project almost every time. I sincerely appreciate his contributions in terms of time and ideas.

I would also like to give my special thanks to Director Dr. Shraddha Arya and HOD Dr. Subhash Chandra for
providing the opportunity and support to me for this work.
I would like to give my sincere thanks to, ……………… Assistant Professor, Department of Computer Science
and Engineering for guidance and support.
I would also offer my deepest gratitude towards the Management of Rajasthan College of Engineering for
Women, Dr. Jitendra Singh Fauzdar and Mrs. Beena Singh, for providing me a spirit to put my every effort
and hard work for the completion of the work.

I also want to thank my all faculty and staff members, friends and family for their encouragement and support.
In particular, I am grateful to my parents for their love and for instilling in me a deep sense of academic pride.

Lastly, I offer my regards and blessings to all of those who supported me in any respect during the completion
of the work.
Jyoti
20ERWCS025

ix
ABSTRACT

This report provides an overview of the Python programming language and its applications. It covers the basics

of Python programming, including data types, control structures, functions, and modules. The report also

discusses advanced topics such as object-oriented programming, file handling, and exception handling. Python

is a high-level, versatile, and widely used programming language known for its simplicity and readability.

Created by Guido van Rossum in the late 1980s, Python has gained immense popularity in various domains,

including web development, data analysis, scientific computing, artificial intelligence, and more. The Python

report delves into the language's key features, applications, and significance in the realm of programming. It

explores Python's versatility, simplicity, and readability, making it an ideal choice for diverse domains such as

web development, data science, and artificial intelligence. The report highlights Python's extensive standard

library and vibrant community support, contributing to its widespread adoption. It also discusses the language's

continuous evolution, with regular updates and enhancements ensuring it remains at the forefront of innovation.

Additionally, the document discusses Python's role in emerging technologies and its continuous evolution,

positioning it as a powerful and adaptable language for both beginners and experienced developers alike.

Python is an object-oriented language that supports multiple programming paradigms such as procedural,

functional, and imperative programming. The report also discusses advanced topics such as object-oriented

programming, file handling, and exception handling. The report also covers Python libraries and frameworks

such as NumPy, Pandas, and Tkinter. NumPy is a fundamental library for scientific computing in Python.

NumPy is essential for data manipulation and numerical computations. NumPy is a powerful library for

numerical computing that provides support for large, multi-dimensional arrays and matrices, along with

mathematical functions to operate on these arrays. Pandas is a popular library for data manipulation and

analysis. It offers data structures like Data Frames and Series, which are used for cleaning, aggregating, and

analyzing data. It provides data structures for efficiently handling large datasets and tools for data cleaning,

exploration, and analysis. Whether for beginners seeking an accessible entry point or seasoned developers

tackling complex projects, Python stands out as a versatile and powerful language with enduring relevance.

1
Chapter-1
INTRODUCTION

1.1 INTRODUCTION TO PYTHON PROGRAMMING


Python is a high-level, versatile, and widely-used programming language known for its simplicity and
readability. Created by Guido van Rossum in the late 1980s, Python has gained immense popularity in various
domains, including web development, data analysis, scientific computing, artificial intelligence, and more.
Python is a dynamic, interpreted (bytecode-compiled) language. There are no type declarations of variables,
parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the
compile-time type checking of the source code. This language supports various programming paradigms,
including procedural, object-oriented, and functional styles, making it adaptable for diverse applications such as
web development, data analysis, and artificial intelligence. Python's extensive standard library and a robust
ecosystem of third-party packages contribute to its popularity, enabling developers to leverage pre-built
functionalities and streamline development. Its interpreted nature allows for quick and interactive coding, and a
supportive community ensures a wealth of resources for both beginners and experienced programmers.

1.2 HISTORY
Python's history dates back to the late 1980s when Guido van Rossum, a Dutch programmer, began working on
a project called the "ABC" language at Centrum Wiskunde & Informatica (CWI) in the Netherlands. The goal
was to create a language that was both easy to use and capable of handling system tasks. However, ABC was
not widely adopted. In December 1989, van Rossum decided to start a new project, influenced by his
experience with ABC. This new language, which he called Python, aimed to combine a clear and readable
syntax with powerful features. The name "Python" was inspired by Monty Python's Flying Circus, a British
comedy group. Python's development continued, and its first public release, Python 0.9.0, came in February
1991. This release included many features that are still part of Python today, such as exception handling,
functions, and modules. The design philosophy of Python, often summarized as "Readability counts" and
"There should be one—and preferably only one— obvious way to do it," contributed to its user-friendly nature.
Python 2 was the primary 2 version for many years, with the final release, Python 2.7, in July 2010. However,
the development community decided to transition to Python 3, introducing some non-backward-compatible
changes to improve the language . Python 3.0, also known as Python 3000 or Py3k, was released in December
2008. While the adoption of Python 3 took time due to compatibility concerns with existing Python 2
codebases, it eventually gained widespread acceptance as the standard. Python's popularity soared in the 2010s,
driven by its simplicity, versatility, and a thriving ecosystem of libraries and frameworks. The language found
extensive use in web development (Django, Flask), data science (NumPy, pandas), machine learning and
artificial intelligence (TensorFlow, Py Torch), automation, and more.

1.3 KEY CONCEPTS


Python is a versatile and popular programming language known for its readability, simplicity, and wide range
of
2
applications. Here are key concepts in Python programming:
• Syntax: Python syntax is clear and readable, emphasizing code readability and allowing developers to express
concepts in fewer lines of code compared to other languages.
• Variables and Data Types: Variables are used to store and manage data. Python supports dynamic typing,
allowing you to assign different data types to variables without explicitly declaring their type. Common data
types include integers, floats, strings, booleans, lists, tuples, sets, and dictionaries.
• Control Flow: Python uses indentation (whitespace) to indicate blocks of code, making it easy to read.
Control flow statements include if, elif, and else for conditional execution, and loops such as for and while for
repetitive tasks.
• Functions: Functions allow you to encapsulate and reuse code. They are defined using the def keyword and
can have parameters and return values.
• Modules and Packages: Python's module system allows you to organize code into reusable files. Multiple
modules can be grouped into packages. The import statement is used to include modules or packages in your
code.
• Lists, Tuples, and Dictionaries: Lists are mutable sequences, tuples are immutable sequences, and dictionaries
are key-value pairs. They provide flexible ways to store and manipulate data.
• Object-Oriented Programming (OOP): Python supports object-oriented programming principles, including
classes and objects. Encapsulation, inheritance, and polymorphism are key concepts in Python OOP.
• Exception Handling: Exception handling is done using try, except, and finally blocks. This helps manage
errors and unexpected situations gracefully.
• File Handling: Python provides various methods for working with files. The open() function is commonly
used to open files, and there are modes like 'r' and there are modes like for reading, 'w' for writing, and 'a' for
appending.
• List Comprehensions: A concise way to create lists. It offers a shorter syntax for creating lists compared to
traditional loops.
• Lambda Functions: Anonymous functions created using the lambda keyword. They are often used for short,
simple operations.
• Decorators: Functions that modify the behaviour of other functions. They are commonly used for tasks such
as logging, timing, or modifying function arguments.
• Generators: Allow the creation of iterators using a special kind of function and the yield keyword. They are
memory-efficient for handling large datasets.
• Virtual Environments: Used to create isolated Python environments for different projects, preventing
conflicts between dependencies.

1.4. POPULARITY
Python programming has enjoyed widespread popularity due to several key factors. It's clear and readable
syntax makes it an accessible language for both beginners and experienced developers, fostering a welcoming
learning
environment. Python's versatility is a significant contributor to its ubiquity, as it finds application across diverse
3
domains, including web development, data science, machine learning, artificial intelligence, scientific
computing, and automation. The language's active and robust community support, evident in the abundance of
libraries, frameworks, and resources available, further propels its popularity. Python's dominance in data
science and machine learning, with widely used libraries such as NumPy, pandas, TensorFlow, and PyTorch,
has solidified its position as a go-to language in these rapidly evolving fields. Additionally, Python's utility in
web development, exemplified by frameworks like Django and Flask, underscores its adaptability. The
language's prevalence in scripting and automation, its use in corporate 4 settings, and its appeal to startups and
innovative projects contribute to sustained demand for Python developers in the job market. The collaborative
spirit fostered by community events and conferences, such as PyCon, further strengthens Python's global
presence. Overall, Python's ease of use, versatility, and strong community support have propelled it to the
forefront of programming languages, making it a top choice for a diverse range of applications.

1.5. IMPORTANCE
Python programming holds immense importance in the field of computer science and various industries. Its
versatility and readability contribute to its widespread adoption, and its significance can be highlighted in
several aspects:
• Ease of Learning and Readability: Python's syntax is clear, concise, and resembles the English language,
making it easy for beginners to learn and understand. Its readability facilitates collaboration among developers,
leading to more maintainable code.
• Versatility and Cross-Industry Applicability: Python is a versatile language with applications across diverse
domains. It is extensively used in web development (Django, Flask), data science (NumPy, pandas), machine
learning (TensorFlow, PyTorch), scientific computing, automation, scripting, and more. Its adaptability allows
developers to switch between different projects and domains seamlessly.
• Data Science and Machine Learning: Python is the language of choice for data science and machine learning
projects. Libraries like NumPy, pandas, and scikit-learn simplify data manipulation and analysis, while
TensorFlow and PyTorch provide powerful tools for building and training machine learning models.
• Web Development: Python frameworks such as Django and Flask have streamlined web development. They
emphasize rapid development, code reusability, and follow the Don't Repeat Yourself (DRY) principle, making
Python an ideal choice for building scalable and maintainable web applications.
• Libraries and Frameworks: Python's rich standard library and a plethora of thirdparty libraries and frameworks
accelerate development. Developers can leverage pre-built modules to enhance functionality, saving time and
effort in project implementation.
• Corporate Adoption: Many large corporations and organizations use Python for various purposes, including
software development, data analysis, and automation. Its readability and maintainability are advantageous for
building and maintaining large-scale projects.
• Startups and Innovation: Python's quick development cycle and the ability to prototype ideas rapidly make it
popular among startups and innovative projects. Its flexibility allows developers to experiment and iterate
4
efficiently.
• Job Market Demand: The demand for Python developers has surged, with many job listings specifying
Python as a required skill. Learning Python enhances one's employability and opens doors to a wide range of
career opportunities.
• Educational Use: Python is widely used in educational settings and is often the language of choice for
introductory programming courses. Its simplicity helps students focus on programming concepts rather than
intricate syntax.
• Cross-Platform Compatibility: Python is compatible with major operating systems, including Windows,
macOS, and Linux. This cross-platform support ensures that Python applications can run seamlessly across
different environments.

1.6 OBJECT ORIENTED PROGRAMMING


Object-Oriented Programming (OOP) in Python is a paradigm that organizes code around the concept of
objects, which encapsulate data and the methods that operate on that data. In Python, everything is an object,
and OOP principles such as encapsulation, inheritance, and polymorphism play a pivotal role in designing and
structuring code. Classes serve as blueprints for creating objects, allowing for the definition of attributes and
behaviours. Encapsulation ensures that the internal details of an object are hidden from the outside world,
promoting data integrity and code modularity.

Inheritance facilitates the creation of new classes based on existing ones, enabling code reuse and the
establishment of a hierarchy of classes. This hierarchy supports the "is-a" relationship, where a derived class
inherits attributes and methods from its base class.

Polymorphism, a key OOP concept, allows objects to be treated as instances of their base class while still
exhibiting their specific behaviours..In Python, creating a class is straightforward, and it allows for the
instantiation of objects with attributes and methods.

The __init__ method serves as a constructor, defining initial attributes when an object is created. Additionally,
Python supports multiple inheritance, enabling a class to inherit from multiple parent classes. Object means a
real-world entity such as a pen, chair, table, computer, watch, etc.
Python supports multiple inheritance, enabling a class to inherit from multiple parent classes. Object means a
real-world entity such as a pen, chair, table, computer, watch, etc.

Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies software development and maintenance by providing some concepts. An Object can be defined as
an instance of a class.
5
An object contains an address and takes up some space in memory. Objects can communicate without knowing
the details of each other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.

OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of
real word problem if we are using the Object-Oriented Programming language.
6

Chapter-2
PYTHON SETUP

2.1 COMMAND LINE BASICS


Command-line basics refer to the fundamental concepts and commands used in a command-line interface (CLI)
or terminal. The command line allows users to interact with a computer by entering text commands instead of
using a graphical user interface (GUI). Here are some key aspects of command-line basics:
• Command Prompt: The command prompt is the text-based interface where users enter commands. It often
displays information about the system, such as the current directory or user.
• Terminal/Shell: The terminal (on Unix-like systems) or command prompt (on Windows) is the application
that provides the command-line interface. Popular terminals include the Unix shell (e.g., Bash) and the
Windows Command Prompt or PowerShell.
• Commands: Commands are text instructions that perform specific tasks. They are entered at the command
prompt to interact with the operating system or execute programs. Commands can be simple, like listing files
(ls or dir), or complex, involving multiple options and arguments.
• Options and Arguments: Options modify the behaviour of a command. They are preceded by a hyphen on
Unix-like systems (e.g., -l for a long listing) or a forward slash on Windows (e.g., /p for pause). Arguments
provide additional information to a command and can be filenames, directory names, or other data.
• File System Navigation: Commands like cd (change directory) are used to navigate the file system. For
example, cd Documents changes the current directory to "Documents."
• File and Directory Operations: Commands like ls (list), mkdir (make directory), cp (copy), mv (move), and rm
(remove) are used to perform operations on files and directories.
• File Viewing and Editing: Commands like cat (concatenate), more, and less are used to view the contents of
files. Text editors like nano, vim, or emacs are used for editing files directly from the command line.
• File Transfer: Commands like scp (secure copy) or rsync are used to transfer files between systems over a
network.
• Process Management: Commands like ps (process status) and kill are used to manage running processes on
the system.
• Redirection and Pipes: Redirection (>, >>) is used to send the output of a command to a file, and pipes (|) are
used to pass the output of one command as input to another.
• Environment Variables: Environment variables store information used by the system or applications.
Commands like echo are used to display the values of environment variables.

2.2 INSTALLING PYTHON


Installing Python is a straightforward process and can be done using different methods depending on your
operating system. Here, I'll outline the general steps for installing Python on Windows:

7
Windows:
Download Python:
• Visit the official Python website at python.org.
• Click on the "Downloads" tab.
• Choose the latest version of Python for Windows (usually displayed prominently).
• Click on the download link, and an installer file (.exe) will be downloaded.
Run the Installer:
• Locate the downloaded installer file.
• Double-click on the file to run the installer.
• Check the box that says "Add Python to PATH" during installation. This makes it easier to run Python
from the command line.
Installation Settings:
• Click "Install Now" to use the default settings.
Complete the Installation:
• Wait for the installation process to finish.
• Once complete, you should see a screen indicating a successful installation.
Verifying the Installation (All Platforms):
• Open Command Prompt/Terminal: Open the command prompt on Windows or the terminal on
macOS/Linux.
• Check Python Version: Run the following command to check the installed Python version:

Figure 2.1 Verifying the Installation

2.3 RUNNING PYTHON CODE


Using an Integrated Development Environment (IDE): Alternatively, you can use an Integrated Development
Environment (IDE) like Visual Studio Code, PyCharm, or Jupyter Notebook to run Python code. Here are the
general steps:
• Open the IDE: Open your preferred Python IDE.
• Create or Open a Python Script: Create a new Python script or open an existing one.
• Run the Script: Most IDEs have a "Run" or "Execute" button. Click this button, or use a keyboard shortcut to
run the script. Check the output in the console or output window.

Chapter-3
CONCEPT OF PYTHON
3.1. VARIABLES
In Python, variables are fundamental components used to store and manage data within a program. Unlike some
statically-typed languages, Python employs dynamic typing, allowing developers to create variables without
specifying their types explicitly. When declaring a variable, you assign it a value, and Python determines its
type based on the assigned value. For instance, an integer, floating-point number, string, boolean, or even a
complex number can be stored in a variable. This flexibility facilitates concise and expressive code.
Variable names in Python follow specific rules: they can consist of letters, numbers, and underscores but cannot
start with a number. Additionally, Python is case-sensitive, treating uppercase and lowercase letters as distinct.
While choosing variable names, it's essential to avoid using reserved words that have predefined meanings in
the language. Variables in Python can be reassigned with new values, allowing for dynamic updates to the data
they represent. This flexibility is particularly useful in scenarios where the value of a variable may change
during program execution.
How Do I Assign a Value to a Variable?
Assigning a value to a variable in Python is an easy process.

You simply use the equal sign = as an assignment operator, followed by the value you want to assign to the
variable. Here's an example:

country = "United States"


year_founded = 1776

In this example, we've created two variables: country and year_founded. We've assigned the string value
"United States" to the country variable and integer value 1776 to the year_founded variable.

There are two things to note in this example:

1. Variables in Python are case-sensitive. In other words, watch your casing when creating variables,
because Year_Founded will be a different variable than year_founded even though they include the
same letters
2. Variable names that use multiple words in Python should be separated with an underscore _. For
example, a variable named "site name" should be written as "site_name". This convention is called
snake case (very fitting for the "Python" language).
How Should I Name My Python Variables?
There are some rules to follow when naming Python variables.

Some of these are hard rules that must be followed, otherwise your program will not work, while others are
known as conventions. This means, they are more like suggestions.

Variable naming rules


3. Variable names must start with a letter or an underscore _ character.
9
Variable names can only contain letters, numbers, and underscores.
4. Variable names cannot contain spaces or special characters.
user_age = 20 # valid
1password = True # invalid

Variable naming conventions


5. Variable names should be descriptive and not too short or too long.
6. Use lowercase letters and underscores to separate words in variable names (known as "snake_case").
What Data Types Can Python Variables Hold?
One of the best features of Python is its flexibility when it comes to handling various data types.

Python variables can hold various data types, including integers, floats, strings, booleans, tuples and lists:

Integers are whole numbers, both positive and negative.

answer = 42

Floats are real numbers or numbers with a decimal point.

weight = 34.592

Strings are sequences of characters, namely words or sentences.

message = "Hello Python"

Booleans are True or False values.

is_authenticated = True

Lists are ordered, mutable collections of values.

fruits = ['apple', 'banana', 'cherry']

Tuples are ordered, immutable collections of values.

point = (3, 4)
3.2. DATATYPES
In Python, data types are fundamental classifications that define the nature of variables and values within a
program. Python is dynamically typed, meaning that the interpreter infers the data type of a variable based on
the value it holds. Several built-in data types are commonly used in Python:
• Integers (int): Integers represent whole numbers without a fractional component. They can be positive or
negative.
Ex: age=25

10
• Floats (float): Floats represent numbers with a decimal point or in scientific notation, allowing for the
representation of both integers and fractions.
Ex: height = 1.75
• Strings (str): Strings are sequences of characters enclosed in single (' ') or double (" ") quotes. They are used to
represent text.
Ex: name = "John"
• Booleans (bool): Booleans represent truth values and can be either True or False. They are often used in
conditional statements and expressions.
Ex: is_student = False
• Lists (list): Lists are ordered and mutable collections that can contain elements of different data types. They
are defined using square brackets.
EX: numbers = [1, 2, 3, 4, 5]
• Tuples (tuple): Tuples are similar to lists but are immutable, meaning their elements cannot be modified once
assigned. They are defined using parentheses.
Ex: coordinates = (3, 5)
• Dictionaries (dict): Dictionaries are unordered collections of key-value pairs. They are defined using curly
braces and colons.
Ex: person = {"name": "Alice", "age": 30, "is_student": True}
• Sets (set): Sets are unordered collections of unique elements. They are defined using curly braces.
Ex: unique_numbers = {1, 2, 3, 4, 5}
• Nontype (None): None is a special constant in Python representing the absence of a value or a null value.

3.3 LIST
In Python, a list is a dynamic and mutable data structure that serves as a container for holding a collection of
items. It is defined by enclosing elements within square brackets [] and separating them with commas. Lists are
versatile and widely used in Python due to their ability to store heterogeneous data types and support various
operations. One of the key features of lists is their indexing, allowing elements to be accessed by their position
in the list. Indices start at 0 for the first element, and negative indices represent positions from the end of the
list. This enables efficient retrieval and manipulation of individual elements. Lists are mutable, meaning that
their elements can be modified after creation. This mutability allows for actions like changing specific
elements, appending new elements, or removing existing ones. Additionally, lists support slicing, enabling the
extraction of sublists based on specified indices. Creating and modifying lists are common tasks in Python
programming. Elements can be added using the append() method or 12 removed using methods like remove()
and pop(). Lists also support various operations such as concatenation and repetition, providing flexibility in
data manipulation. List comprehensions are a concise and powerful feature in Python for creating lists. They
offer a syntactically compact way to generate lists based on specified conditions or transformations. Nested
lists, where a list contains other lists, allow for the creation of multidimensional structures. This is particularly
useful for representing
11
matrices or tables within a single list.

Figure 3.1 Basic List Operations


3.3.1 Operation of list
Operations on lists in Python encompass a variety of functionalities, allowing for dynamic manipulation,
retrieval, and modification of data stored in a list.
Here's an elaborate overview of key list operations:
• Creating a List: This initializes a list named fruits containing strings.

Figure 3.2 Creating a List


• Accessing Elements: Accessing elements using indices, where fruits [0] retrieves the first element, fruits [1]
retrieves the second, and fruits [-1] retrieves the last.

Figure 3.3 Accessing Elements


• Slicing: Slicing creates a sublist containing elements at indices 1 and 2.

Figure 3.4 Slicing


• Modifying Elements: Modifying an element in the list by assigning a new value to a specific index.

12

Figure 3.5 Modifying Elements


• Adding Elements: Appending adds an element to the end, while insert adds an element at a specified index.

Figure 3.6 Adding Elements


• Removing Elements: Removing elements: remove removes a specified value, pop removes and returns an
element at a specific index, and del deletes an element at a specified index.

Figure 3.7 Removing Elements


• Finding Elements: Checking if an element is present (in) and finding the index of a specific value.

Figure 3.8 Finding Elements


• Length of a List: Finding the number of elements in a list using the len() function.

Figure 3.9 Length of List


• List Methods: List methods include sorting and reversing the order of elements in-place

Figure 3.10 List Methods


• Nested Lists: Creating a nested list, where each element is a list itself.

13

Figure 3.11 Nested Lists


• List Comprehensions: List comprehensions provide a concise way to create lists based on specified conditions
or transformations.

Figure 3.12 List Comprehensions


These operations showcase the versatility of lists in Python. Lists provide a powerful and flexible mechanism
for storing and manipulating data, making them essential for various programming tasks, from basic data
storage to complex algorithm implementations. Understanding these operations enables efficient use of lists in
diverse programming scenarios.

3.4 TUPLE
In Python, a tuple is a versatile and immutable data structure used to store an ordered collection of elements.
Tuples are defined by enclosing elements within parentheses () and separating them with commas. The key
characteristics of tuples are their immutability, meaning once created, their elements cannot be modified, and
their ordered nature, which preserves the sequence of elements. Creating a tuple is straightforward, and
elements within it can be of different data types, allowing for flexibility in representing diverse information.

Figure 3.13 Creating a Tuple


Accessing elements in a tuple is done through indexing, starting from 0 for the first element. The immutability
of tuples ensures that their elements cannot be changed after creation. Tuples support operations such as
concatenation and repetition, enabling the creation of new tuples by combining existing ones. Tuple packing
and unpacking are common practices.
14

Figure 3.14 Basic Tuple Operations


Tuple packing involves creating a tuple without using parentheses, while tuple unpacking allows for extracting
elements into separate variables. The len() function calculates the number of elements in a tuple, and methods
like count() and index() provide additional functionalities. Tuples find application in scenarios where
immutability 15 is advantageous, such as representing fixed collections of values or serving as keys in
dictionaries. Their ordered nature and ability to hold a variety of data types make them valuable in different
programming contexts. Understanding the characteristics and use cases of tuples enhances the effectiveness of
Python programs.

3.5 DIFFERENCE BETWEEN LIST AND TUPLE


Table 3.1 Difference between List and Tuple
The choice between lists and tuples depends on the specific requirements of your program. Use lists when you
need a mutable collection and use tuples when you want an immutable collection. Each has its advantages, and
understanding their differences helps in making informed design decisions.
15
3.6 DICTIONARIES
In Python, dictionaries serve as versatile and dynamic data structures, allowing the storage and retrieval of
information through key-value pairs. This data type is defined by enclosing the pairs within curly braces {},
with each key associated with a specific value separated 16 by a colon. The hallmark feature of dictionaries lies
in their ability to provide efficient and direct access to data based on unique identifiers—the keys. For instance:
person = {"name": "John", "age":30, "city": "New York"}
Here, "name," "age," and "city" are keys, each associated with their respective values. The mutability of
dictionaries permits the addition, modification, or removal of key-value pairs, enhancing adaptability during
program execution. Dictionaries can be nested, allowing the creation of hierarchical structures. This nesting
capability is advantageous for representing complex relationships within data. Built-in methods facilitate
various operations on dictionaries, including adding or removing items and obtaining lists of keys or values.
Iterating through dictionaries enables the retrieval of keys, values, or both, providing flexibility in processing
data. Conditional checks, such as determining the existence of a key, can be performed using the in keyword.
Additionally, dictionary comprehensions offer a concise syntax for creating dictionaries based on specific
conditions or transformations. Dictionaries find application in scenarios where data organization involves key-
value associations. Common use cases include representing entities, configurations, or relationships between
different pieces of information. A solid understanding of dictionaries is crucial for effective data manipulation
and storage in Python, as they play a fundamental role in various programming tasks.

3.7 OPERATORS IN PYTHON


In Python, basic operators are fundamental elements that allow for the manipulation and computation of values.
These operators perform operations on variables and values, and they can be categorized into different types,
including arithmetic, comparison, logical, assignment, and more.

Figure 3.15 Operators in Python

16

• Arithmetic Operators: Arithmetic operators are used for mathematical operations, such as addition,
subtraction, multiplication, division, and modulus.

Figure 3.16 Arithmetic Operators

• Comparison Operators: Comparison operators are used to compare values and return Boolean results.

Figure 3.17 Comparison Operators

• Logical Operators: Logical operators are used to combine conditional statements.


Figure 3.18 Logical Operators

• Assignment Operators: Assignment operators are used to assign values to variables.

Figure 3.19 Assignment Operators

• Bitwise Operators: Bitwise operators perform bit-level operations on integers.

17

Figure 3.20 Bitwise Operator

• Identity Operators: Identity operators are used to compare the memory locations of two objects.

Figure 3.21 Identity Operators


Table 3.2 Description of Operators

3.8 CONTROL STRUCTURES

In Python, control structures are integral components that enable the logical flow and execution of code. These
structures include conditional statements, loops, and exception handling, providing mechanisms for decision
making, iteration, and error management.

Conditional Statements: Conditional statements, like if, elif (else if), and else, allow programmers to execute
specific blocks of code based on certain conditions. This enables the creation of dynamic and responsive
programs that respond to varying inputs or states.

18

Loops: Loops, such as for and while, facilitate the repetition of code. for loops iterate over sequences or
iterable objects, executing a block of code for each element, while while loops continue execution as long as a
specified condition holds true. These structures empower developers to perform repetitive tasks efficiently.

Exception Handling: Exception handling, implemented with try, except, else, and finally blocks, provides a
systematic approach to managing errors in a program. It allows 19 developers to anticipate and gracefully
handle unexpected situations, ensuring the robustness and reliability of their code.

These control structures collectively contribute to the readability, flexibility, and functionality of Python
programs. They empower developers to create logical and organized code that responds dynamically to
different scenarios, making Python a versatile and expressive programming language. Understanding and
skilfully employing these control structures are essential aspects of proficient Python programming.

3.7.1 Loops in Python


In Python, loops are essential constructs that facilitate the repetition of code, enabling efficient iteration over
sequences or execution of a block of code as long as a specified condition holds true. Two primary types of
loops are employed: for loops and while loops.

For Loops: for loops are particularly useful for iterating over sequences, such as lists, tuples, or strings. The
loop iterates over each element in the sequence, executing a specified block of code for each iteration.

Figure 3.22 For Loops

While Loops: while loops continue to execute a block of code as long as a specified condition remains true.
This type of loop is often used when the number of iterations is not known in advance.

Figure 3.23 While Loops

3.9 FUNCTIONS

In Python, functions are fundamental units of code that encapsulate a specific task or set of instructions,
promoting modularity, reusability, and maintainability in programming. Functions are defined using the def
keyword, followed by the function name and a set of parameters enclosed in parentheses. The function body

19

contains the code to be executed when the function is called, and it is indented to signify its scope.

Figure 3.24 Functions


Functions play a pivotal role in organizing code, promoting code reuse, and enhancing readability. They allow
developers to break down complex problems into smaller, manageable tasks. Understanding and leveraging
functions is a core skill in Python programming, contributing to the creation of modular and maintainable code.

3.10 PYTHON EXCEPTIONS HANDLING

An exception is an error which happens at the time of execution of a program. However, while running a
program, Python generates an exception that should be handled to avoid our program to crash. In Python
language, exceptions trigger automatically on errors.

The exception indicates that, although the event can occur, this type of event happens infrequently. When the
method is not able to handle the exception, it is thrown to its caller function. Eventually, when an exception is
thrown out of the main function, the program is terminated abruptly.

Common Examples of Exception


 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a non-existent index of a sequence
 Removing the table from the disconnected database server
 ATM withdrawal of more than the available amount

Why should you use Exceptions?


 Exception handling allows you to separate error-handling code from normal code.
 An exception is a Python object which represents an error.
 As with code comments, exceptions helps you to remind yourself of what the program expects.
20

 It clarifies the code and enhances readability.


 Allows you to stimulate consequences as the error-handling takes place at one place and in one manner.
 An exception is a convenient method for handling error messages.
 In Python, you can raise an exception in the program by using the raise exception method.
 Raising an exception helps you to break the current code execution and returns the exception back to
exception until it is handled.
 Processing exceptions for components which can’t handle them directly.

Python Exception Handling Mechanism


Exception handling is managed by the following 5 keywords:
1. try
2. catch
3. finally
4. throw
Python Try Statement
A try statement includes keyword try, followed by a colon (:) and a suite of code in which exceptions may
occur. It has one or more clauses.

During the execution of the try statement, if no exceptions occurred then, the interpreter ignores the exception
handlers for that specific try statement.

In case, if any exception occurs in a try suite, the try suite expires and program control transfers to the matching
except handler following the try suite.

Figure 3.25 Try Statement

The catch Statement


Catch blocks take one argument at a time, which is the type of exception that it is likely to catch. These
arguments may range from a specific type of exception which can be varied to a catch-all category of
exceptions.

21

Figure 3.26 Catch Statement


Finally Statement in Python
Finally block always executes irrespective of an exception being thrown or not. The final keyword allows you
to create a block of code that follows a try-catch block.

Finally, clause is optional. It is intended to define clean-up actions which should be that executed in all
conditions.

Figure 3.27 Finally Statement

Raise Statement in Python


The raise statement specifies an argument which initializes the exception object. Here, a comma follows the
exception name, and argument or tuple of the argument that follows the comma.

Figure 3.28 Raise Statement

22

Python Errors
Figure 3.29 Python Errors

3.11 Errors vs. Exceptions

Table 3.3 Difference Between Errors and Exceptions

23

Chapter-4
WORKING WITH LIBRARIES
4.1 PYTHON LIBRARIES
In Python, libraries are collections of pre-written code modules that provide a range of functionalities, allowing
developers to extend the capabilities of their programs without having to build everything from scratch. These
libraries cover diverse domains, from mathematics and data manipulation to web development and machine
learning, offering a wealth of tools and resources. Some prominent Python libraries include:
• NumPy: NumPy is a powerful library for numerical computing that provides support for large,
multidimensional arrays and matrices, along with mathematical functions to operate on these arrays. It is widely
used in scientific computing, data analysis, and machine learning.
NumPy in Python is a library that is used to work with arrays and was created in 2005 by Travis Oliphant.
NumPy library in Python has functions for working in domain of Fourier transform, linear algebra, and
matrices. Python NumPy is an open-source project that can be used freely. NumPy stands for Numerical
Python.
Installing NumPy:
Installing the NumPy library is a straightforward process. You can use pip to install the library. Go to the
command line and type the following:

Figure 4.1 Install NumPy

NumPy is a library for the Python programming language, and it’s specifically designed to help you work with
data.
With NumPy, you can easily create arrays, which is a data structure that allows you to store multiple values in a
single variable.
In particular, NumPy arrays provide an efficient way of storing and manipulating data.NumPy also includes a

24
number of functions that make it easy to perform mathematical operations on arrays. This can be really useful
for scientific or engineering applications. And if you’re working with data from a Python script, using NumPy
can make your life a lot easier.
• pandas: pandas is a data manipulation library that provides data structures like DataFrame for efficient data
analysis. It is particularly valuable for handling and cleaning structured data, making it a go-to tool in data
science and analytics.
Pandas is a powerful and versatile library that simplifies tasks of data manipulation in Python . Pandas is built
on top of the NumPy library and is particularly well-suited for working with tabular data, such as spreadsheets
or SQL tables. Its versatility and ease of use make it an essential tool for data analysts, scientists, and engineers
working with structured data in Python.
What can you do using Pandas?
 Data set cleaning, merging, and joining.
 Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
 Columns can be inserted and deleted from DataFrame and higher dimensional objects.
 Powerful group by functionality for performing split-apply-combine operations on data sets.
 Data Visulaization
Installing Pandas
The first step of working in pandas is to ensure whether it is installed in the system or not. If not then we need
to install it in our system using the pip command. Type the cmd command in the search box and locate the
folder using the cd command where python-pip file has been installed. After locating it, type the command:

Figure 4.2 Installing pandas


Importing Pandas
After the pandas have been installed into the system, you need to import the library. This module is generally
imported as follows:

Figure 4.3 Importing pandas


Here, pd is referred to as an alias to the Pandas.
• Matplotlib: Matplotlib is a popular data visualization library in Python. It allows the creation of various
types of plots and charts, making it an essential tool for visualizing data trends and patterns.
Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest benefits of
visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib
25
consists of several plots like line, bar, scatter, histogram, etc.
Installation:
Windows, Linux, and macOS distributions have Matplotlib and most of its dependencies as wheel packages.
Run the following command to install the Matplotlib package. But before that make sure Python and PIP are
already installed on a system:
After checking Python and PIP in your system, We need to run this command to install Matplotlib.

Figure 4.4 Installing Matplotlib


Importing Matplotlib

Figure 4.5 Importing Matplotlib


Types of Matplotlib
 Matplotlib Line Plot
 Matplotlib Bar Plot
 Matplotlib Histograms Plot
 Matplotlib Scatter Plot
 Matplotlib Pie Charts
 Matplotlib Area Plot

• Tkinter: Tkinter is Python's standard GUI library, which comes with Python's standard library. It provides a
simple and easy way to create desktop applications with graphical interfaces. Tkinter is well-suited for smaller
projects and applications with basic GUI requirements.
It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python tkinter is the fastest and
easiest way to create GUI applications. Creating a GUI using tkinter is an easy task.
To create a tkinter Python app:
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets.
The name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.

Figure 4.6 Importing Tkinter


26
There are two main methods used which the user needs to remember while creating the Python application with
GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter
offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name
of the window, you can change the className to the desired one. The basic code used to create the main
window of the application is:
2. mainloop(): There is a method known by the name mainloop() is used when your application is ready to run.
mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as
long as the window is not closed.
Tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the
parent windows. There are mainly three geometry manager classes class.

1. pack() method: It organizes the widgets in blocks before placing in the parent widget.
2. grid() method: It organizes the widgets in grid (table-like structure) before placing in the parent widget.
3. place() method: It organizes the widgets by placing them on specific positions directed by the
programmer.
• Flask and Django: Flask and Django are web development frameworks that simplify the process of building
web applications in Python. Flask is a lightweight framework, while Django provides a more comprehensive
solution, including an ORM (Object-Relational Mapping) system and an admin interface.
Flask: Initially launched in 2010 by Armin Ronacher, Flask is known as a micro-framework as it has little or
no dependencies on external libraries. Using it, developers have the flexibility of choosing design patterns,
tools, and databases. Thus, flexibility is the main feature of this python framework.
Since the web development industry is now leaning more towards micro-services and server-less platforms,
Flask’s popularity is continuously rising. It is widely used for building scalable web applications effortlessly.
All thanks to its unique features.
Features of Flask
 Built-in development server and a fast debugger
 High scalability as it is a component-based framework
 It uses Jinja2 templates and is WSGI 1.0 compliant.
 RESTful request dispatching
 ORM-agnostic and highly flexible
 HTTP request handling functionality
 Provides support for unit testing
 Easy to deploy in production

Django: Launched in 2005, Django is a full-stack framework designed with the primary goal of making the
27
development of complex database-driven websites easy. It facilitates secure and faster development by freeing
developers from performing repetitive web development tasks. With many excellent features, it enables
developers to create robust and high-performing applications.
Another USP of the Django framework is that it is an easy-to-scale and secure web framework, so it is perfect
for developing enterprise-level applications. Supporting multiple formats (like XML, HTML, JSON, etc.),
Django lets developers focus on developing the web apps’ business logic and eliminates the need to create apps
from scratch.
Features of Django
 A batteries-included framework
 Allows rapid development
 Easy to scale and extend
 Highly secure and versatile
 Supports multiple databases
 Provides support for many front-end tools
 Large and helpful Community

• TensorFlow and PyTorch: These are libraries specifically designed for machine learning and deep learning.
TensorFlow is developed by Google, and PyTorch is maintained by Facebook. Both are widely used for
building and training neural networks.
TensorFlow: Just like PyTorch, it is also an open-source library used in machine learning. It was developed by
Google and was released in 2015. Its name itself expresses how you can perform and organize tasks on data.
Production and research are the main uses of Tensorflow. Neural networks mostly use Tensorflow to develop
machine learning applications.
PyTorch: It is an open-source library used in machine learning. It was developed by Facebook and was released
to the public for the first time in 2016. It is imperative which means it runs immediately and the user can check
if it is working or not before writing the full code. We can write a part of code and check it in real time, it is
built-in python based implementation to provide compatibility as a deep learning platform. It rapidly gained
users because of its user-friendly interface.
• Beautiful Soup: Beautiful Soup is a library for web scraping purposes. It provides tools for pulling data out
of HTML and XML files, making it useful for extracting information from websites.
Beautiful Soup is a Python library for getting data out of HTML, XML, and other markup languages. Say
you’ve found some webpages that display data relevant to your research, such as date or address information,
but that do not provide any way of downloading the data directly. Beautiful Soup helps you pull particular
content from a webpage, remove the HTML markup, and save the information. It is a tool for web scraping that
helps you clean up and parse the documents you have pulled down from the web.
28
Install Beautiful Soup:
Step 1: Installing the required third-party libraries

Easiest way to install external libraries in python is to use pip. pip is a package management system used to
install and manage software packages written in Python. All you need to do is:

Figure 4.7 Installing Beautiful Soup


Step 2: Accessing the HTML content from webpage
Step 3: Parsing the HTML content
• OpenCV: OpenCV (Open Source Computer Vision Library) is a computer vision library that provides tools
for image and video analysis. It is widely used in fields such as robotics, facial recognition, and object
detection. and build robust solutions across various domains.
OpenCV is an open-source software library for computer vision and machine learning. The OpenCV full form
is Open-Source Computer Vision Library. It was created to provide a shared infrastructure for applications for
computer vision and to speed up the use of machine perception in consumer products. OpenCV, as a BSD-
licensed software, makes it simple for companies to use and change the code. There are some predefined
packages and libraries that make our life simple and OpenCV is one of them.
Install OpenCV:
To install OpenCV, one must have Python and PIP, preinstalled on their system.
Downloading and Installing OpenCV:
OpenCV can be directly downloaded and installed with the use of pip (package manager). To install OpenCV,
just go to the command-line and type the following command:

Figure 4.8 Installing OpenCV


To check if OpenCV is correctly installed, just run the following commands to perform a version check:
Figure 4.9 Checking installation of OpenCV
29
The Python library ecosystem contributes significantly to the language's popularity and widespread adoption in
different industries.

4.2 WORKING OF PYTHON LIBRARY


A Python library is a collection of pre-written code and functionalities. The developers can use this to simplify
and streamline their programming tasks. Generally, developers create Python libraries to handle specific
domains or supply general-purpose functionality.
Developers can drag and drop reusable modules, classes, methods, and data structures from these libraries into
their Python programs.
When a library gets imported, its code becomes available within the program. It permits the developers to
leverage its capabilities without writing the code from scratch. Libraries are often distributed and installed using
package managers like pip.
It fetches the required library files from online repositories.
The MS Windows environment recognizes library files with the DLL (Dynamic Load Libraries) extension. The
linker automatically explores the required library when we run our program and import a library. It then
integrates the functions from the library into our program, authorizing us to use them. Using library strategies in
our program makes accessing and using pre-written code easier.
Python libraries deliver a broad range of functionalities, such as data manipulation, scientific computing, web
development, machine learning, and more. This helps the developers to build robust and efficient applications
by using the existing code and tools provided by the library.

4.3 USE OF LIBRARIES IN PYTHON


As we write large-size programs in Python, we want to maintain the code’s modularity. For the easy
maintenance of the code, we split the code into different parts and we can use that code later ever we need it. In
Python, modules play that part.
Instead of using the same code in different programs and making the code complex, we define mostly used
functions in modules and we can just simply import them in a program wherever there is a requirement. We
don’t need to write that code but still, we can use its functionality by importing its module. Multiple interrelated
modules are stored in a library. And whenever we need to use a module, we import it from its library. In
Python, it’s a very simple job to do due to its easy syntax. We just need to use import.
In the realm of machine learning, the Scikit-learn library is widely employed. It offers a comprehensive set of
machine learning algorithms and tools for tasks such as classification, regression, clustering, and model
evaluation. Developers can utilize Scikit-learn to build, train, and evaluate machine learning models with
relative ease.
Moreover, libraries like Flask empower web developers by simplifying the creation of web applications. Flask
is a micro web framework that streamlines the process of handling HTTP requests and building web servers,
making web development more accessible.
30
For scientific computing, the SciPy library builds upon NumPy and provides additional functionality for
optimization, integration, interpolation, and more. This makes it a valuable resource for researchers and
engineers working on complex scientific and technical problems. Additionally, in the domain of graphics and
plotting, Matplotlib stands out as a versatile 2D plotting library. It enables the creation of high-quality charts
and figures, supporting a wide range of visualization needs.

4.4 WEB SCRAPPING IN PYTHON


Web scraping in Python involves the extraction of data from websites by programmatically navigating the
HTML and CSS structure of web pages. This process is facilitated by various Python libraries, commonly
including Requests for making 24 HTTP requests and BeautifulSoup or Scrapy for parsing HTML content.
Web scraping is a technique used to extract data from websites.
Python is a popular language for web scraping because it has many libraries that make it easy to scrape
websites Beautiful Soup. Beautiful Soup is a Python library used to pull the data out of HTML and XML files
for web scraping purposes. It produces a parse tree from page source code that can be utilized to drag data
hierarchically and more legibly . Another popular library for web scraping in Python is Requests . Requests
library is used for making HTTP requests to a specific URL and returns the response. Python requests provide
inbuilt functionalities for managing both the request and response .
To perform web scraping using Requests and Beautiful Soup, you can follow these steps:
• Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by
returning the HTML content of the webpage. This can be done using the Requests library.
• Parse the HTML content of the webpage. This can be done using Beautiful Soup. Beautiful Soup creates a
parse tree from the HTML content of the webpage, which can be used to extract data from the webpage.
• Find the data you want to extract. This can be done using Beautiful Soup. Beautiful Soup provides several
methods for searching the parse tree to find the data you want to extract.
• Extract the data you want. Once you have found the data you want to extract, you can extract it using
Beautiful Soup.
• Store the data in a structured format. Once you have extracted the data you want, you can store it in a
structured format such as a CSV file or a database.
4.4.1 Why is Web Scraping Used?
• Price Comparison: Services such as ParseHub use web scraping to collect data from online shopping websites
and use it to compare the prices of products.
• Email address gathering: Many companies that use email as a medium for marketing, use web scraping to
collect email ID and then send bulk emails.
• Social Media Scraping: Web scraping is used to collect data from Social Media websites such as Twitter to
find out what’s trending.
• Research and Development: Web scraping is used to collect a large set of data (Statistics, General 25
Information, Temperature, etc.) from websites, which are analyzed and used to carry out Surveys or for R&D.
31
• Job listings: Details regarding job openings, interviews are collected from different websites and then listed in
one place so that it is easily accessible to the user.

4.5 WORKING WITH IMAGES IN PYTHON


Python has several libraries that make it easy to work with images. One of the most popular libraries for
working with images in Python is Pillow . Pillow is a fork of the Python Imaging Library (PIL) and provides
support for opening, manipulating, and saving many different image file formats . Here are some of the things
you can do with images in Python using Pillow:
• Opening and Displaying Images: You can use Pillow to open and display images in Python. Pillow supports
many different image file formats, including JPEG, PNG, BMP, and GIF.
• Resizing and Cropping Images: You can use Pillow to resize and crop images in Python. Pillow provides
several methods for resizing and cropping images, including resize(), thumbnail(), and crop().
• Rotating and Flipping Images: You can use Pillow to rotate and flip images in Python. Pillow provides several
methods for rotating and flipping images, including rotate(), transpose(), and mirror().
• Adding Text and Watermarks to Images: You can use Pillow to add text and watermarks to images in Python.
Pillow provides several methods for adding text and watermarks to images, including ImageDraw.Draw.text()
and ImageDraw.Draw.multiline_text().

4.6 WORKING WITH PDF FILES IN PYTHON


Working with PDF files in Python involves using libraries that provide functionalities for reading,
manipulating, and creating PDF documents. One popular library for this purpose is PyPDF2. Here's an
overview of working with PDF files in Python using PyPDF2:
• Install PyPDF2: Make sure PyPDF2 is installed using the following command : For example: jyoti>pip install
PYPDF2

Figure 4.10 Install PyPDF2


• Reading PDF Files: PyPDF2 allows you to read text content from existing PDF files. Here's a simple
example:

32

Figure 4.11 Reading PDF Files


Merging PDF Files: PyPDF2 allows you to merge multiple PDF files into a single document.Here's an example:

Figure 4.12 Merging PDF Files


• Creating PDF Files: You can use PyPDF2 to create new PDF files and add content to them. Here's a simple
example:

Figure 4.13 Creating PDF Files


Working with PDF files in Python is made accessible by libraries like PyPDF2, enabling developers to
manipulate PDF documents for tasks ranging from text extraction to merging and creating new PDFs. Keep in
mind that PyPDF2 may have limitations for handling certain PDF features, and for more complex tasks, other
libraries like PyMuPDF (MuPDF) or pdfplumber might be considered. Additionally, ensure compliance with
any licensing or legal requirements when working with PDF files.

33
4.7. GRAPHICAL USER INTERFACE
A graphical user interface (GUI) is a digital interface in which a user interacts with graphical components such
as icons, buttons, and menus. Python has several libraries that make it easy to create graphical user interfaces
(GUIs). One of the most popular libraries for creating GUIs in Python is Tkinter . Tkinter is a built-in Python
library that provides a simple way to create GUIs. Tkinter provides several widgets, such as buttons, labels, and
text boxes, that you can use to create your GUI. You can also use Tkinter to create menus, dialog boxes, and
other GUI elements. Another popular library for creating GUIs in Python is PyQt . PyQt is a set of Python
bindings for the Qt application framework and runs on all platforms supported by Qt, including Windows, OS
X, Linux, iOS, and Android. PyQt provides a wide range of widgets, including buttons, labels, and text boxes,
that you can use to create your GUI. PyQt also provides support for creating menus, toolbars, and other GUI
elements. Another popular library for creating GUIs in Python is wxPython . wxPython is a set of Python
bindings for the wxWidgets C++ toolkit. wxPython provides a wide range of widgets, including buttons, labels,
and 28 text boxes, that you can use to create your GUI. wxPython also provides support for creating menus,
toolbars, and other GUI elements. Finally, another popular library for creating GUIs in Python is PySimpleGUI.
PySimpleGUI is a new Python GUI library that has been gaining a lot of interest recently. PySimpleGUI
provides a simple way to create GUIs in Python. PySimpleGUI provides several widgets, including buttons,
labels, and text boxes, that you can use to create your GUI. PySimpleGUI also provides support for creating
menus, toolbars, and other GUI elements.

4.8. SCOPE OF PYTHON


The scope defines the accessibility of the Python object. You must define the scope to access a particular
variable in the code, as it cannot be accessed from anywhere in the program. Scope is the specific coding region
that defines the visibility of variables. Variables are not visible to the entire code; programmers can restrict their
visibility. Scope determines which variables are ‘seen’. The scope defines the set of rules which tell us how and
where a variable can be searched. You search the variable either to retrieve or assign a value. The namespace is
the unique identification of the variable or the method. Namespace tells the Python interpreter about the name
of the object and the location from where it is trying to access it. The LEGB rule searches the Namespaces for
scope resolution. The LEGB stands for: L: Local, E: Enclosed, G: Global, B: built in. The sequence of LEGB is
important. First, the program searches for the variable in the local scope, then in the enclosed scope, followed
by the global scope, and finally in the built-in scope. In Python, there are four types of scopes, which are as
follows:
• Global Scope
• Local Scope
• Enclosing Scope
• Built-in Scope
• Global Scope
Global scope refers to the names of variables which are defined in the main body of a program. These are
visible and accessed throughout the program. The variables or objects declared in the global scope are easily
accessible
34
to all functions within the program.
• Local Scope
• Local scope refers to the names which are defined within a function and are local to that function. They can be
accessed from the point of its definition until the end of the block in which it has been defined. The local scope
exists till the time the function has been executed. Let’s understand the local scope with the help of a code
• Enclosing Scope or Non-local Scope
Enclosing scope is also known as non-local scope. They refer to the names of a variable defined in the nested
function. Simply put, these variables are neither present in the local scope nor in the global scope. To create a
non-local variable in an enclosing scope, use a non-local keyword. Let’s understand the enclosing scope with
the help of a code.
• Built-in Scope
When the variable or object is not found in local, global, or enclosing scope, then Python starts looking for it in
the built-in scope. Built-in scopes are one of the widest scopes that cover all the reserved keywords. These are
easy to call anywhere in the program prior to using them, without the need to define them.

4.9. APPLICATION OF PYTHON PROGRAMMING


• Python is a versatile programming language that has a wide range of applications. Here are some of the most
popular applications of Python:
• Web Development: Python is widely used in web development. It makes use of simple code to build a
beautiful and functional website. It has related libraries and modules like HTTP, XML, JSON, IMAP, POP,
FTP, etc. These help in storage in databases, content management, and interfacing with internet protocols. It
also has frameworks integrated with it like Django, Flask, Pyramid, and Bottle. In addition, Python also comes
with packages like Beautiful Soup, Twisted Python, and Feedparser.
• Artificial Intelligence and Machine Learning: Many AI and ML models are built using Python. Data analysts
use it too. The fundamental cause for this is the availability of many tools and libraries specific to these
applications.
Some of them include: Pandas for Data Manipulation and Analysis. NumPy and SciPy for 30 mathematical
computations. Seaborn and Matplotlib for visualization. Scikit learn, Tensor Flow, Keras for algorithms.
• Game Development: One of the interesting applications of the Python Programming language is to build
games like egg catcher, snake game, etc. Python comes with packages like Pygame and Pykyra to build
awesome games. It facilitates the development of 3D games with respective libraries. It is also used for
scripting in many game engines. Famous games like Battlefield 2, World of Tanks, Toontown Online, and
Civilization 4 are also built using Python.
• Desktop GUI Development: Its simplicity and platform independence nature make it a good choice for GUI
applications. Though Tkinter is the standard library for GUI development, there are other supporting libraries
like: W x Python Kivy PyQt, PySide PyGUI Delphi GTK+.
• Enterprise/ Business Applications: Business applications are developed keeping in mind the comfort and ease
35
of usage by the organization. Python’s features like scalability, extensibility, and readability make it the best
choice for business applications. The following used Python: Odoo: This is an all-in-one business management
software for enterprising purposes. Tryton: general-purpose, high level, third-tier business application.
• Software Development: Python supports the development of software with its libraries and packages. It is
used for building, testing, management, and so on. For example, Scons help in build control Buildbot and
Apache are used for autonomous and continuous testing. Roundup and Trac test and manage errors.
• Educational Purposes: Python helps beginners get introduced to the Programming environment. It is because
of its simple syntax and beginner friendly nature. Another reason could be its scope and reach in the
development community.

Figure 4.14 Application of Python Programming


36

CHAPTER 5
CONCLUSION AND FUTURE WORK

5.1 Conclusion and Contribution


Python is a versatile programming language that has a wide range of applications. It is widely used in web
development, artificial intelligence and machine learning, game development, desktop GUI development,
enterprise/business applications, software development, and educational purposes.
Python is also easy to learn and use, making it a great way to learn how to code. Python has a lot of libraries
and tools that make it easy to work with images, PDF files, and web scraping. It is also a great language for
creating graphical user interfaces (GUIs) and games. Python is widely used in artificial intelligence and
machine learning, and it is a great language for data analysis and visualization. Python is also used in
enterprise/business applications and software development.
Python is a great language for beginners because it is easy to learn and use, and it has a wide range of
applications. It is also a great language for experts because it is versatile and has a lot of libraries and tools that
make it easy to work with different types of data and applications.
In conclusion, Python is a popular programming language due to its ease of use, versatility, and wide range of
applications in various fields. It is a great choice for beginners and experts alike, and its popularity is only
expected to grow in the coming years.
The uses of Python in different areas can be attributed to the simplicity of its syntax, scalability, being an
open-source, object-oriented, and easy to learn programming language. Let’s know more about the uses of
Python in the real-world which has made this language popular and the preference of almost every coder today
especially those in the field of Artificial Intelligence and Data Science.

1. Web Development
Famously known as the go-to programming language for web development, Python has an important role to
play in it. Python comes with multiple web development frameworks like Pyramid, Django, and Flask. These
frameworks are packed with standard libraries that allow easy protocol integration and lead to a reduction in
development time.
2. Data Science
We all know that data science is one of the most in-demand skills in the market. Knowledge of data science is a
sought-after skill in IT, manufacturing, or eCommerce. This is where Python steps in. Its multiple libraries,
such as Pandas, TensorFlow, NumPy, etc help in extracting valuable information from the data. Libraries
like Matplotlib and Seaborn further allow a data science professional to focus on data visualization
through graphs and charts. It won’t be an exaggeration to say that Python is the first thing that any data science
professional needs to know.

37

3. Artificial Intelligence and Machine Learning


One of the most important uses of Python is in AI. The reason for it is that Python is a stable language that has
the capacity to handle the computations required to build machine learning models. Its libraries like
Keras, Pandas, NumPy and others are suitable for machine learning applications. Furthermore, it is used in
multiple AI solutions like advanced computing, image recognition, data processing, and more.
4. Enterprise Applications
Enterprise applications are used to serve the needs of an organization rather than individual users. The use of
Python in building enterprise applications is done as it is a robust language that can handle multiple
requests of databases at once. Even though the use of Python varies from one enterprise to another, its core
functionalities like its readability, functionality, and scalability remain the same. Enterprise applications are
one of the most notable uses of Python. Tryton and Odoo are platforms that help in developing such enterprise
applications.
5. Education Sector
One of the other important uses of Python is seen in developing online courses and education programs. It is an
easy to learn programming language for beginners since its syntax matches that of English. It offers a novice,
a standard library, and a variety of resources to understand the language, thus making the learning curve
easier. This is one of the many reasons why Python is the preferred programming language for beginners for
the education program’s development at both basic and advanced levels.
6. Web Scraping Applications
It refers to the scraping of huge quantities of data by companies for extracting customer information to make
profitable decisions. Tools like PythonRequest, Selenium, MechanicalSoup are used in Python programming
for building web scraping applications. Thanks to Python’s ability to build software that can process large
amounts of data, this language is a clear winner in making web scraping applications.
7. Game Development
This one had to be featured in the top 10 uses of Python. And why not? Python has time and again displayed its
capacity of contributing to the gaming industry in a massive way. Remember Battlefield 2; one of the most
popular games in the early 2000s? It was developed using the Python programming language. Some of the top
Python frameworks that are used in game development include Pygame, PyKyra, Pyglet, PyOpenGL, Kivy,
Panda3D, Cocos2D, and more!
8. Software Development
One of the prime uses of Python is that it is used by software developers. Python simplifies the software
development process for complex apps. It is used for project management, as a support programming
language, to build control, and testing.
9. Desktop GUI
One of the top uses of Python is developing a desktop GUI. We know that Python is a simple, stable, easy to
learn, open-source, and platform-independent programming language. These factors work in their favour
of being used for developing desktop GUI. Toolkits like PyQt, PyGUI, and WxPython are widely used for
38
building high-quality GUIs efficiently.
10. Operating Systems
Python is a powerful programming language and so is C. When these two are combined together, many
operating systems are developed. The use of Python in creating operating systems came to life with Ubuntu’s
Ubiquity, and Red Hat’s Anaconda and Fedora. OS made with Python are running billions of computers
today.

5.2 Future Scope


The future and the scope of Python programming looks promising, as Python continues to be one of the most
widely used and popular programming languages. Here’s a comprehensive guide to understanding the future
trends and opportunities for Python:

1. Data Science and Machine Learning:


Python’s dominance in data science and machine learning is expected to continue in 2023. It will likely remain
the go-to language for data analysis, visualization, and implementing machine learning models.
The demand for Python frameworks and libraries like TensorFlow, PyTorch, and scikit-learn is expected to
grow, as businesses increasingly leverage AI and machine learning for decision-making and automation.
2. Web Development and Frameworks:
Python web frameworks such as Django and Flask are likely to maintain their popularity in 2023, as they offer
robustness, scalability, and ease of use.
With the growing need for real-time web applications, asynchronous frameworks like FastAPI, Tornado, and
Quart may gain more traction, providing high-performance and scalable solutions.
3. Serverless Computing:
The rise of serverless computing, where developers focus on writing code without worrying about infrastructure
management, is expected to create opportunities for Python.
Python, with its simplicity and ease of use, could be a popular choice for developing serverless functions and
applications using platforms like AWS Lambda, Google Cloud Functions, and Azure Functions.
4. Quantum Computing:
Quantum computing is an emerging field that holds great potential. While Python is not the primary language
for quantum computing, it is expected to have libraries and tools that facilitate quantum programming.
Quantum computing libraries like Qiskit and PyQuil already have Python APIs, making it easier for developers
to experiment with quantum algorithms and simulations.
5. Cross-Platform and Mobile Development:
Python frameworks like Kivy, BeeWare, and PySide2 allow developers to create cross-platform desktop and
mobile applications.
As businesses aim to reach users on various devices, Python’s cross-platform compatibility may see increased
adoption for developing mobile apps, desktop applications, and GUI interfaces.
39

6. IoT and Edge Computing:


Python’s versatility and ease of use make it a suitable language for programming IoT devices and interacting
with edge computing platforms.
MicroPython, a lightweight implementation of Python, is specifically designed for microcontrollers and can be
utilized in IoT projects.
With the growth of IoT and the need for intelligent edge devices, Python may find more applications in this
space.
7. Continued Community Growth and Collaboration:
Python has a thriving community that contributes to its growth, development, and ecosystem.
Online resources, open-source projects, and community-driven initiatives will continue to provide avenues for
learning, collaboration, and innovation.
The Python Software Foundation (PSF) and Python Enhancement Proposals (PEPs) will likely play a vital role
in shaping the language’s future.
Remember that these trends are speculative, and the actual trends in 2023 may vary. It’s essential to stay
updated with the latest developments, follow industry influencers, participate in Python conferences, and
continuously enhance your skills to leverage the opportunities that emerge in the Python programming field.
40

REFERENCES

https://www.geeksforgeeks.org/python-lists/
https://www.w3schools.com/python/python_intro.asp
https://www.geeksforgeeks.org/libraries-in-python/
https://www.codingninjas.com/studio/library/python-libraries-and-their-features
https://medium.com/@techyfygeeks/future-scope-and-trends-in-python-programming-in-2023-
fa8a38a50f3e
41

You might also like