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

unit-1 python

The document outlines a programming course in Python, covering data structures, GUI applications, and database connectivity. It includes an introduction to Python's history, syntax rules, data types, and practical exercises for implementing various Python functionalities. Key topics include built-in functions, data analysis, and visualization using libraries like pandas and matplotlib.

Uploaded by

sibi00424
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit-1 python

The document outlines a programming course in Python, covering data structures, GUI applications, and database connectivity. It includes an introduction to Python's history, syntax rules, data types, and practical exercises for implementing various Python functionalities. Key topics include built-in functions, data analysis, and visualization using libraries like pandas and matplotlib.

Uploaded by

sibi00424
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 118

S11BLH21 PROGRAMMING IN PYTHON - 4

COURSE OBJECTIVES
 To learn about data structures lists, tuples, and dictionaries in Python.
 To build packages with Python modules for reusability and handle user/custom exceptions.
 To create real world GUI applications, establish Database connectivity and Networking
UNIT 1 INTRODUCTION TO PYTHON 12 Hrs.
History of Python- Introduction to the IDLE interpreter (shell) - Data Types - Built-in function – Conditional
statements - Iterative statements- Input/output functions - Python Database Communication - data analysis
and visualization using python.
Practical:
 Implement built-in functions and trace the type of data items.
 Implement concepts of Conditional and Iterative Statements.
 Use the built-in csv module to read and write from a CSV file in Python.
 Perform data analysis and visualization on a given dataset using Python libraries like pandas, numpy,
matplotlib and display charts, graphs, and plots.

K.Abinaya Assistant Professor SBU


History of Python
• Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
Major Python Releases
Python 0.9.0
• Python's first published version is 0.9. It was released in February
1991. It consisted of support for core object-oriented programming
principles.
Python 1.0
• In January 1994, version 1.0 was released, armed with functional
programming tools, features like support for complex numbers etc.
K.Abinaya Assistant Professor SBU
Python 2.0
 Next major version − Python 2.0 was launched in October 2000. Many new features
such as list comprehension, garbage collection and Unicode support were included
with it.
Python 3.0
 Python 3.0, a completely revamped version of Python was released in December
2008. The primary objective of this revamp was to remove a lot of discrepancies
that had crept in Python 2.x versions.
 Python 3 was backported to Python 2.6. It also included a utility named
as python2to3 to facilitate automatic translation of Python 2 code to Python 3.
Current Version
 Meanwhile, more and more features have been incorporated into Python's 3.x
branch. As of date, Python 3.11.2 is the current stable version, released in February
2023.

K.Abinaya Assistant Professor SBU


IDLE Software in Python
 IDLE stands for Integrated Development and Learning Environment.
 The lightweight and user-friendly Python IDLE (Integrated Development and
Learning Environment) is a tool for Python programming.
 Since version 1.5.2b1, the standard Python implementation has included IDLE,
an integrated development environment.
 Many Linux distributions include it in the Python packaging as an optional
component.
 The Tkinter GUI toolkit and Python are used throughout.

K.Abinaya Assistant Professor SBU


Python Syntax Rules

 -Python is case sensitive. Hence a variable with


name “python” is not same as pYThon.
 -For path specification, python uses forward slashes.
Hence if you are working with a file, the default path for the
file in case of Windows OS will have backward slashes,
which you will have to convert to forward slashes to make
them work in your python script
 -Eg: For window's path C:\folderA\folderB relative
python program path should be C:/folderA/folderB

K.Abinaya Assistant Professor SBU


• In python, there is no command terminator, which means no
semicolon ; or anything. So if you want to print something as
output, all you have to do is:

In one line only a single executable statement should be written and the line change act
as command terminator in python.
To write two separate executable statements in a single line, you should use
a semicolon ;
to separate the commands.
For example,

K.Abinaya Assistant Professor SBU


Execute Python Syntax

• As we learned in the previous page, Python syntax can


be executed by writing directly in the Command Line:

Or by creating a python file on the server, using


the .py file extension, and running it in the
Command Line:

K.Abinaya Assistant Professor SBU


Python Indentation

• Indentation refers to the spaces at the beginning


of a code line.
• Where in other programming languages the
indentation in code is for readability only, the
indentation in Python is very important.
• Python uses indentation to indicate a block of
code.
Example
if 5 > 2:
print("Five is greater than two!")

K.Abinaya Assistant Professor SBU


• Python will give you an error if you skip the indentation:

Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")

K.Abinaya Assistant Professor SBU


Points to Remember while Writing a Python Program

• Case sensitive
• Punctuation is not required at end of the statement
• In case of string use single or double quotes i.e. ‘
’ or “ ”
• Must use proper indentation
• Python Program can be executed in two different
modes:
• Interactive Mode Programming
• Script mode programming

K.Abinaya Assistant Professor SBU


Expressions
• In Python, operators are special symbols that designate that some
sort of computation should be performed. The values that an
operator acts on are called operands.

>>> a = 10
>>> b = 20
>>> a + b
30

K.Abinaya Assistant Professor SBU


In this case, the + operator adds the
operands a and b together. An operand can be either a
literal value or a variable that references an object:
>>> a = 10
>>> b = 20
>>> a + b - 5
25

K.Abinaya Assistant Professor SBU


Python Data Types

• Variables can hold values, and every value has a data-type. Python is a
dynamically typed language; hence we do not need to define the type of the
variable while declaring it. The interpreter implicitly binds the value with its
type.
a=5
• The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.
• Python enables us to check the type of the variable used in the program.
Python provides us the type() function, which returns the type of the
variable passed.

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
Numbers:
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type.
Python provides the type() function to know the data-type of the variable.
1.Int - 10, 2, 29, -20, -150 etc.
2.Float - 1.9, 9.902, 15.2, etc.
3.complex - x + iy where x and y denote the real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.

K.Abinaya Assistant Professor SBU


Slicing

K.Abinaya Assistant Professor SBU


Slicing Example

K.Abinaya Assistant Professor SBU


Sequence Type
1.String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns
'Python Python’.

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
2.List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator
(+) and repetition operator (*) works with the list in the same way as they were working
with the strings.

K.Abinaya Assistant Professor SBU


3.Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple
consists of a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

K.Abinaya Assistant Professor SBU


Python Ranges
Python range() is an in-built function in Python which returns a sequence of
numbers starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Python Dictionary
 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).

K.Abinaya Assistant Professor SBU


Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false.
It denotes by the class bool. True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F'.

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Python Data Type Conversion
1. Conversion to int

2. Conversion of Float

K.Abinaya Assistant Professor SBU


Data Type Conversion Functions
Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.

2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.

3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.

K.Abinaya Assistant Professor SBU


9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.

12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.

15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.

17 oct(x)
Converts an integer to an octal string.
K.Abinaya Assistant Professor SBU
Set
 Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements.
 In set, the order of the elements is undefined; it may return the changed sequence
of the element. The set is created by using a built-in function set(), or a sequence of
elements is passed in the curly braces and separated by the comma. It can contain
various types of values.

K.Abinaya Assistant Professor SBU


Built-in Data Types

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

K.Abinaya Assistant Professor SBU


Example Data Type
x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

K.Abinaya Assistant Professor SBU


x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", frozenset


"cherry"})

x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

x = None NoneType

K.Abinaya Assistant Professor SBU


Setting the Specific Data Type

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range
K.Abinaya Assistant Professor SBU
x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Maximum of two
numbers in Python

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Data Conversion
int(x)
Converts x into integer
whole number
float(x)
Converts x into floating point
number

str(x)
Converts x into a string
representation

K.Abinaya Assistant Professor SBU


chr(x)
Converts integer x into a
character

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
Variable Names in Python
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

K.Abinaya Assistant Professor SBU


Many Values to Multiple Variables

One Value to Multiple Variables

K.Abinaya Assistant Professor SBU


Unpack a Collection

K.Abinaya Assistant Professor SBU


Output Variables

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be
done with casting. Python is an object-orientated language, and as such it uses classes
to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
•int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
•float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
•str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

K.Abinaya Assistant Professor SBU


Python Strings-Strings are Arrays

K.Abinaya Assistant Professor SBU


String Length

Check String

K.Abinaya Assistant Professor SBU


Check if NOT

K.Abinaya Assistant Professor SBU


Python - Modify Strings

Remove Whitespace
-strip() method removes any whitespace from the beginning or the end:

K.Abinaya Assistant Professor SBU


Replace String
The replace() method replaces a string with another string:

Split String
The split() method returns a list where the text between the specified separator becomes
the list items.

K.Abinaya Assistant Professor SBU


String Concatenation

To add a space between them, add a " ":

K.Abinaya Assistant Professor SBU


Input/Output

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Python Operators
Python divides the operators in the following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators

K.Abinaya Assistant Professor SBU


Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
K.Abinaya Assistant Professor SBU
Python Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
K.Abinaya Assistant Professor SBU
Python Comparison Operators

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y

< Less than x<y


>= Greater than or equal to x >= y

<= Less than or equal to x <= y

K.Abinaya Assistant Professor SBU


Python Logical Operators

Operator Description Example

and Returns True if both x < 5 and x < 10


statements are true

or Returns True if one of x < 5 or x < 4


the statements is true

not Reverse the result, not(x < 5 and x < 10)


returns False if the result
is true

K.Abinaya Assistant Professor SBU


Python Identity Operators
Operator Description Example
is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same x is not y
object

Python Membership Operators

Operator Description Example


in Returns True if a sequence with the specified value is present in the x in y
object

not in Returns True if a sequence with the specified value is not present in x not in y
the object

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Python Conditions and If statements

Elif
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".

K.Abinaya Assistant Professor SBU


Else
The else keyword catches anything which isn't caught by the preceding conditions.

K.Abinaya Assistant Professor SBU


Short Hand If

One line if else statement, with 3 conditions

K.Abinaya Assistant Professor SBU


AND NOT

OR

K.Abinaya Assistant Professor SBU


The pass Statement
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.

K.Abinaya Assistant Professor SBU


Python Loops
Python has two primitive loop commands:
•while loops
•for loops
while Loop

With the while loop we can execute a set of statements as long as a condition is true.

K.Abinaya Assistant Professor SBU


Break Statement
With the break statement we can stop the loop even if the while condition is true:

Continue Statement
With the continue statement we can stop the current iteration, and continue with the
next:Continue to the next iteration if i is 3:

K.Abinaya Assistant Professor SBU


Else Statement
With the else statement we can run a block of code once when the condition no longer is
true:

K.Abinaya Assistant Professor SBU


Python For Loops
 A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
 This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
 With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

K.Abinaya Assistant Professor SBU


Looping Through a String
• Even strings are iterable objects, they contain a sequence of characters:

Break Statement
• With the break statement we can stop the loop before it has looped through all the
items:

K.Abinaya Assistant Professor SBU


 Exit the loop when x is "banana", but this time the break comes before the print:

Continue Statement:
 With the continue statement we can stop the current iteration of the loop, and continue
with the next:

K.Abinaya Assistant Professor SBU


The range() Function
 To loop through a set of code a specified number of times, we can use
the range() function,
 The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

K.Abinaya Assistant Professor SBU


Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Break the loop when x is 3, and see what happens with the else block:

K.Abinaya Assistant Professor SBU


Nested Loops
The "inner loop" will be executed one time for each iteration of the
"outer loop":

K.Abinaya Assistant Professor SBU


PYTHON FUNCTIONS
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:

Calling a Function
To call a function, use the function name followed by parenthesis:

K.Abinaya Assistant Professor SBU


Arguments
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
 The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:

K.Abinaya Assistant Professor SBU


 A parameter is the variable listed inside the parentheses in the function
definition.
 An argument is the value that is sent to the function when it is called.
Number of Arguments
 By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

K.Abinaya Assistant Professor SBU


Arbitrary Arguments, *args
 If you do not know how many arguments that will be passed into your function, add a
* before the parameter name in the function definition.
 This way the function will receive a tuple of arguments, and can access the items
accordingly:
 If the number of arguments is unknown, add a * before the parameter name:

K.Abinaya Assistant Professor SBU


Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.

K.Abinaya Assistant Professor SBU


Arbitrary Keyword Arguments, **kwargs
 If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
 This way the function will receive a dictionary of arguments, and can access the
items accordingly:
 If the number of keyword arguments is unknown, add a double ** before the
parameter name:

K.Abinaya Assistant Professor SBU


Default Parameter Value
 If we call the function without argument, it uses the default value:

K.Abinaya Assistant Professor SBU


Passing a List as an Argument
 You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.
 E.g. if you send a List as an argument, it will still be a List when it reaches the function:

K.Abinaya Assistant Professor SBU


Return Values
To let a function return a value, use the return statement:

The pass Statement


function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.

K.Abinaya Assistant Professor SBU


Python program to find the largest number among the three input numbers

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
Input & Output Statements
Input – to read values from the user
Syntax:
Variable=input()
Input() – function used to read values
Output- to display the result
Syntax:
print(“hello students”)
print(“welcome”)
Print(“value is”,x)

K.Abinaya Assistant Professor SBU


Input from User in Python
Sometimes a developer might want to take user input at some point in the program. To
do this Python provides an input() function.
Syntax:
input('prompt’)
Example 1: Python get user input with a message

K.Abinaya Assistant Professor SBU


Example 2: Integer input in Python

How to take Multiple Inputs in Python :


we can take multiple inputs of the same data type at a time in python, using map()
method in python.

K.Abinaya Assistant Professor SBU


Inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
1.Taking List/Set elements one by one by using the append()/add() methods.
2.Using map() and list() / set() methods.

K.Abinaya Assistant Professor SBU


Using map() and list() / set() Methods

Output using print() function


Python print() function prints the message to the screen or any other standard output device.
Parameters:
object - value(s) to be printed
sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add add specific values like new line "\n", tab "\t"
file (optional) - where the values are printed. It's default value is sys.stdout (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
Separator
The print() function can accept any number of positional arguments. To separate these
positional arguments , keyword argument “sep” is used.

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
Python Database
Communication

K.Abinaya Assistant Professor SBU


Introduction to Databases
As said above, a database is the collection of data in a structured manner for
easy access and management. We have various database management systems which
include:
1. MySQL
2. Oracle Database
3. SQL server
4. Sybase
5. Informix
6. IBM db2
7. NO SQL
We will be using the MySQL database system since it is easier and convenient to
use. It uses the SQL (Structured Query Language) to do operations like creating,
accessing, manipulating, deleting, etc., on the databases.

K.Abinaya Assistant Professor SBU


Python Modules to Connect to MySQL
To communicate with MySQL Python provides the below modules:
1. MySQL Connector Python
2. PyMySQL
3. MySQLDB
4. MySqlClient
5. OurSQL

All the above modules have almost the same syntax and methods to handle the
databases.

K.Abinaya Assistant Professor SBU


Communication Between Python and MySQL
Python communicates with MySQL by forming a connection with it. The process of
communication happens in the following steps:

3. Then we use the connect() method to send the connection request


to Mysql. This function returns an MYSQL Connection object on a
successful connection.

4. After this, we call the cursor() method to further do various


operations on the database. K.Abinaya Assistant Professor SBU
5. Now we can execute various operations and get the
results by giving the query to the execute the () function.

6. We can also read the result by using the functions


cursor.fetchall() or fetchone() or fetchmany().

7. When we are done working with the database we can


close the cursor and the connection using the functions
cursor.close() and connection.close().

K.Abinaya Assistant Professor SBU


Connecting to the MySQL
the first step after importing the module is to send the connection request using the
connect() method. This function takes the following arguments:
1. Username: It is the username that one uses to work with MySQL server. The
default username is root.
2. Password: This is the password given by the user when one is installing the
MySQL database.
3. Host Name: This is the server name or IP address on which MySQL is running. We
can either give it as ‘localhost’ or 127.0.0.0
4. Database name: This is the name of the database to which one wants to connect.
This is an optional parameter.

K.Abinaya Assistant Professor SBU


K.Abinaya Assistant Professor SBU
K.Abinaya Assistant Professor SBU
Data Visualization using Matplotlib in Python
 Matplotlib is a versatile and widely-used data visualization library in Python. It allows
users to create static, interactive, and animated visualizations.
 The library is built on top of NumPy, making it efficient for handling large datasets.
 This library is built on the top of NumPy arrays and consist of several plots like line
chart, bar chart, histogram, etc. It provides a lot of flexibility but at the cost of writing
more code.
Installing Matplotlib for Data Visualization

If you are using Jupyter Notebook, you can install it within a notebook cell by using:

K.Abinaya Assistant Professor SBU


Data Visualization With Pyplot in Matplotlib
Matplotlib provides a module called pyplot, which offers a MATLAB-like interface for creating plots and
charts. It simplifies the process of generating various types of visualizations by offering a collection of
functions that handle common plotting tasks.
Category Function Description

Plot Creation plot() Creates line plots with customizable styles.

scatter() Generates scatter plots to visualize relationships.

Graphical Elements bar() Creates bar charts for comparing categories.

hist() Draws histograms to show data distribution.

pie() Creates pie charts to represent parts of a whole.

Customization xlabel(), ylabel() Sets labels for the X and Y axes.

title() Adds a title to the plot.

legend() Adds a legend to differentiate data series.

Visualization Control xlim(), ylim() Sets limits for the X and Y axes.

grid() Adds gridlines to the plot for readability.

show() Displays the plot in a window.

Figure Management figure() Creates or activates a figure.

subplot() Creates a grid of subplots within a figure.


K.Abinaya Assistant Professor SBU
savefig() Saves the current figure to a file.
1. Line Chart
Line chart is one of the basic plots and can be created using the plot() function. It is used
to represent a relationship between two data X and Y on a different axis.

K.Abinaya Assistant Professor SBU


2. Bar Chart
A bar chart is a graph that represents the category of data with rectangular bars with
lengths and heights that is proportional to the values which they represent. The bar
plots can be plotted horizontally or vertically. A bar chart describes the comparisons
between the discrete categories. It can be created using the bar() method.

K.Abinaya Assistant Professor SBU


3. Histogram
A histogram is basically used to represent data provided in a form of some groups. It is a
type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency. The hist() function is used to compute and create histogram
of x.

K.Abinaya Assistant Professor SBU


4. Scatter Plot
Scatter plots are used to observe relationships between variables. The scatter() method
in the matplotlib library is used to draw a scatter plot.

K.Abinaya Assistant Professor SBU


5. Pie Chart
Pie chart is a circular chart used to display only one series of data. The area of slices of
the pie represents the percentage of the parts of the data. The slices of pie are called
wedges. It can be created using the pie() method.

K.Abinaya Assistant Professor SBU


6. Box Plot
A Box Plot, also known as a Whisker Plot, is a standardized way of displaying the
distribution of data based on a five-number summary: minimum, first quartile (Q1),
median (Q2), third quartile (Q3), and maximum. It can also show outliers.

K.Abinaya Assistant Professor SBU

You might also like