You are on page 1of 43

PYTHON PROGRAMMING

A
Industrial Training report
Submitted
in partial fulfillment
for the award of the degree of

Bachelor of Technology
in Department of Computer Science & Engineering

Supervisor: Submitted By:


Name: Ravi Kumar Name :Ayan Chouhan
Designation: Lead R&D Roll no: 21ESBCS009

Department of Computer Science and Engineering


Sri Balaji College of Engineering & Technology, Jaipur
RTU
NOVEMBER, 2023
CERTIFICATE

i
CANDIDATE’S DECLARATION

I hereby declare that the work, which is being presented in the dissertation , entitled
“PYTHON DEVELOPMENT” in partial fulfillment for the award of Degree of “Bachelor
of Technology” in Department of Computer Science Engineering and submitted to the
Department of Computer Science Engineering, SRI BALAJI COLLEGE OF
ENGINEERING AND TECHNOLOGY, Rajasthan Technical University, is a record of my
own investigations carried under the Guidance of Mr. Ravi Kumar, Lead R&D at JDB
INFOTECH PVT LTD.
I have not submitted the matter presented in this seminar/project any where for the award
of any other Degree.

AYAN CHOUHAN

Computer Science Engineering


Enrollment No.: 21E1SBCSF40P009
Sri Balaji college of Engineering and Technology, Jaipur

ii
ACKNOWLEDGEMENT

I acknowledge the guidance and support of my instructor Mr. Ravi Kumar who taught me
the fundamentals of Python and its applications. I have taken efforts in this dissertation .
However, it would not have been possible without the kind support of many individuals. I
would like to extend my sincere thanks to all of them.
It has been great honor and privilege to undergo training at JDB INFOTECH PVT LTD. I
am highly indebted to Mr. Ravi Kumar for their guidance and constant supervision as well
as for providing necessary information regarding the project and also for their support in
completing this project. He gave me constructive suggestions and motivated me to improve
my skills and knowledge. I also appreciate the assistance and cooperation of the other
members and colleagues at JDB INFOTECH PVT LTD, who helped me in completing this
training successfully . I also appreciate the friendly and supportive environment that they
created for me and the other trainees. I would also like to acknowledge the contribution of
my fellow trainees, who shared their experiences and insights with me and helped me learn
from their perspectives and feedback. I enjoyed working and collaborating with them on
various projects and assignments during the training.
And last but not the least, I thank my family and friends, who supported me throughout the
training and motivated me to pursue my goals and interests. They were always there for me
with their love and care, and inspired me to do my best. I dedicate this training report to
them.

Submitted By:
AYAN CHOUHAN

iii
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.

iv
LIST OF FIGURES

Figure Title Page


Fig. 1.1 Concept of python 5
Fig. 2.1 Verifying the Installation 7
Fig 3.1 Creating a List 11
Fig. 3.2 Accessing Elements 11
Fig. 3.3 Slicing 11
Fig. 3.4 Modifying Elements 11
Fig. 3.5 Adding Elements 11
Fig. 3.6 Removing Elements 11
Fig. 3.7 Finding Elements 12
Fig. 3.8 Length of a list 12
Fig. 3.9 List Methods 12
Fig. 3.10 Nested Lists 12
Fig. 3.11 List Comprehensions 12
Fig. 3.12 Creating a tuple 13
Fig. 3.13 Arithmetic Operators 15
Fig. 3.14 Comparison Operators 15
Fig. 3.15 Logical Operators 15
Fig. 3.16 Assignment Operators 15
Fig. 3.17 Bitwise Operators 16
Fig. 3.18 Identity operator 16
Fig. 3.19 For loops 17

v
Fig. 3.20 While loops 17
Fig. 3.21 Function 18
Fig. 4.1 Install PyPDF2 23
Fig. 4.2 Reading PDF Files 24
Fig. 4.3 Merging PDF Files 24
Fig. 4.4 Creating PDF Files 25
Fig. 4.5 Application of python programming 28

vi
LIST OF TABLES

Table Title Page


Table 3.4 : Difference between list and tuple 13
Table 3.6 : Operators 16

vii
TABLE OF CONTENT
Title Page
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
4.2. Working of libraries 22

viii
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
Conclusion 32
Reference 33

ix
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
1
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 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.

2
• 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 behavior 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. Its 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 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

3
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 third-
party libraries and frameworks accelerate development. Developers can leverage
pre-built modules to enhance functionality, saving time and effort in project
implementation.

4
• 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 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 behaviors.
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 behaviors..In Python, creating a class is
straightforward, and it allows for the instantiation of objects with attributes and methods.

5
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. 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.

Fig. 1.1: Concept of oops

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 behavior 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.

7
• 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 :
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, or customize the installation by
clicking "Customize installation."
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):

8
• 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:

Fig 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.

9
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.

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
• 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.

10
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}
• NoneType (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

11
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 matrices or tables
within a single list.
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.

Fig 3.1: 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.

Fig 3.2 : Accessing Elements


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

Fig 3.3 : Slicing


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

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

Fig 3.5 : 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.

Fig 3.6 : Removing Elements


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

Fig 3.7 : Finding Elements


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

Fig 3.8 :
Length of a list
• List Methods: List methods include sorting and reversing the order of elements in-
place.

Fig 3.9: List Methods


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

13
Fig 3.10 : Nested Lists
• List Comprehensions: List comprehensions provide a concise way to create lists
based on specified conditions or transformations.

Fig 3.11 : 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.3 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.

Fig 3.12 : 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. 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

14
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.4 DIFFERENCE BETWEEN LIST AND TUPLE

LIST TUPLE
Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


Consuming. comparitively faster.
The list is better for performing operations A tuple data type is appropriate for
such as insertion and deletion accessing the elements.
Lists consume more memory Tuple consume lesser memory
Lista have several built-in methods Tuples does not have many built-in
methods
Unexpected changes and errors are more In a tuple,it is hartd to take place
likely to occur

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.

3.5 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

15
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.6 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.
• Arithmetic Operators: Arithmetic operators are used for mathematical operations,
such as addition, subtraction, multiplication, division, and modulus.

Fig 3.13 : Arithmetic Operators


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

16
Fig 3.14 : Comparison Operators

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

Fig 3.15 : Logical Operators

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

Fig 3.16 : Assignment Operators

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

Fig 3.17 : Bitwise Operators

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

17
Fig.3.18:IdentityOperator

Table 3.2
Description of operators

3.7 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 decisionmaking, 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.
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

18
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 skillfully 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.

Fig 3.19 : 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.

Fig 3.20 : While Loops

3.8 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 contains the code to be executed
when the function is called, and it is indented to signify its scope.

19
Fig 3.21 : 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.

20
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.
• 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.
• 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.
• 4.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 wellsuited for smaller projects and applications
with basic GUI requirements.
• 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.
• 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.

21
• 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.
• 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. 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.

22
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.
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

23
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

24
Information, Temperature, etc.) from websites, which are analyzed and used to
carry out Surveys or for
R&D.
• 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

25
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: ayanchouhan>pip install PYPDF2
• Reading PDF Files: PyPDF2 allows you to read text content from existing
PDF files. Here's a simple example:

Fig 4.2 : Reading PDF Files

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

Fig 4.3 : 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:

26
Fig 4.4 : 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.

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
27
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
to all functions within the program.

28
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.7. 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

29
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: Wx
Python Kivy PyQt, PySide PyGUI Delphi GTK+.
• Enterprise/ Business Applications: Business applications are developed keeping
in mind the comfort and ease 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.

30
Fig 4.5 : Application of python programming

31
CONCLUSION

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 1. 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.

32
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

33

You might also like