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

PYTHON LAB MANUAl

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, mathematics, and system scripting. It features a simple syntax, supports multiple programming paradigms, and has built-in data types and operators for various operations. The document also covers Python's conditional statements, iterators, and provides examples of using different operators and data types.

Uploaded by

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

PYTHON LAB MANUAl

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, mathematics, and system scripting. It features a simple syntax, supports multiple programming paradigms, and has built-in data types and operators for various operations. The document also covers Python's conditional statements, iterators, and provides examples of using different operators and data types.

Uploaded by

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

What is Python?

Python is a popular programming language. It was created by Guido van Rossum,


and released in 1991.

It is used for:

● web development (server-side),


● software development,
● mathematics,
● system scripting.

What can Python do?


● Python can be used on a server to create web applications.
● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify files.
● Python can be used to handle big data and perform complex mathematics.
● Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.

Good to know
● The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
● In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny, Pycharm,
Netbeans or Eclipse which are particularly useful when managing larger
collections of Python files.

Python Syntax compared to other programming


languages
● Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
● Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.

Python Data Types


Built-in Data Types
In programming, data type is an important concept.

Variables can store data of different types, and different types can do different
things.

Python has the following data types built-in by default, in these categories:

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

1. Write a program to demonstrate different number


data types in python
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))

Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>

In the above example, we have created three variables


named num1, num2 and num3 with values 5, 5.0, and 1+2j respectively.
We have also used the type() function to know which class a certain variable
belongs to.
Since,

● 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
● 2.0 is a floating value, type() returns float as the class of num2 i.e <class
'float'>
● 1 + 2j is a complex number, type() returns complex as the class
of num3 i.e <class 'complex'>

Python Operators
Operators are special symbols that perform operations on variables and values.
For example,
print(5 + 6) # 11
Run Code

Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators


Here's a list of different types of Python operators that we will learn in this
tutorial.

1. Arithmetic Operators

2. Assignment Operators

3. Comparison Operators

4. Logical Operators

5. Bitwise Operators

6. Special Operators

Python Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc. For example,

sub = 10 - 5 # 5
Here, - is an arithmetic operator that subtracts two values or variables.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16

2. Write a program to demonstrate Arithmetic operators


in python

a=7
b=2
# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division
print ('Floor Division: ', a // b)

# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)

Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
In the above example, we have used multiple arithmetic operators,

● + to add a and b
● - to subtract b from a
● * to multiply a and b
● / to divide a by b
● // to floor divide a by b
● % to get the remainder
● ** to get a to the power b

Python Assignment Operators


Assignment operators are used to assign values to variables. For example,

# assign 5 to x
x=5
Here, = is an assignment operator that assigns 5 to x.
Here's a list of different assignment operators available in Python.

Operator Name Example


= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10

3. Write a program to demonstrate Assignment


operators in python
# assign 10 to a
a = 10

# assign 5 to b
b=5

# assign the sum of a and b to a


a += b #a=a+b

print(a)

Output: 15

Here, we have used the += operator to assign the sum of a and b to a.


Similarly, we can use any other assignment operators as per our needs.
Python Comparison Operators
Comparison operators compare two values/variables and return a boolean
result: True or False. For example,
a=5
b=2

print (a > b) # True


Here, the > comparison operator is used to compare whether a is greater
than b or not.
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True

4. Write a program to demonstrate comparison


operators in python

a=5

b=2

# equal to operator
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)
# less than or equal to operator
print('a <= b =', a <= b)
Run Code

Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False

Python Logical Operators


Logical operators are used to check whether an expression is True or False.
They are used in decision-making. For example,
a=5
b=6

print((a > 2) and (b >= 6)) # True


Run Code

Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the
result is True.
Operator Example Meaning
Logical AND:
and a and b True only if both the operands are True
Logical OR:
or a or b True if at least one of the operands is True
Logical NOT:
not not a True if the operand is False and vice-versa.

5. Write a program to demonstrate logical operators in


python
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True

# logical NOT
print(not True) # False

Python Bitwise operators


Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x 0010 1000)

Python Special operators

Python language offers some special types of operators like


the identity operator and the membership operator. They are described below
with examples.
Identity operators
In Python, is and is not are used to check if two values are located at the same
memory location.
It's important to note that having two variables with equal values doesn't
necessarily mean they are identical.

Operator Meaning Example


is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same
is not object) x is not True

6. Write a program to demonstrate identity operators in


python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False

Output:

False
True
False

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:

● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
7. Write a program to demonstrate conditions and if
statements in python
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
b is greater than a

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

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Output:
a and b are equal

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

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Output:

a is greater than b
And
The and keyword is a logical operator, and is used to combine conditional
statements:

Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Output:
Both conditions are True

Or
The or keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Output:
At least one of the conditions is True

Nested If
You can have if statements inside if statements, this is called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Output:
Above ten,
and also above 20!

8. Write a program to demonstrate Python iterators.


Python Iterators

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.

Technically, in Python, an iterator is an object which implements the iterator protocol,


which consist of the methods __iter__() and __next__().

Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output:
apple
banana
cherry
Even strings are iterable objects, and can return an iterator:

Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Output:
b
a
n
a
n
a

Looping Through an Iterator


We can also use a for loop to iterate through an iterable object:

Example
Iterate the values of a tuple:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)

Output:
apple
banana
cherry

Create an Iterator
To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you to do some initializing when the object is
being created.

The __iter__() method acts similar, you can do operations (initializing etc.), but must
always return the iterator object itself.

The __next__() method also allows you to do operations, and must return the next
item in the sequence.

Example
Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

Output:
1
2
3
4
5

9. Write a program to demonstrate Python modules.


Python Modules
What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your


application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)
Use a Module

Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("SSIT")
Output:
Hello, SSIT

Variables in Module

The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
Output:
36

Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.

Example
Import and use the platform module:

import platform

x = platform.system()
print(x)

Output:
Windows

Import From Module


You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])
Output:
36

10.Write a program to demonstrate Strings in python


Strings

Strings in python are surrounded by either single quotation marks, or double


quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')
Output:
Hello
Hello
Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:

Example
a = "Hello"
print(a)

Output:
Hello
Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a
string with a length of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output:
e
String Length

To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Output:
13
11.Write a program to demonstrate Tuples in python.

Python Tuples
mytuple = ("apple", "banana", "cherry")

Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Output:
('apple', 'banana', 'cherry')

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.

Example
One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Output:
<class 'tuple'>
<class 'str'>

Tuple Items - Data Types

Tuple items can be of any data type:

Example
String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

Output:
('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)

Python Lists
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

12.Write a program to create, append, and remove


lists in python.
SOURCECODE:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list) # Output: 'o'
print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm']
print(my_list) # Output: 'm'
print(my_list.pop()) # Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear() # Output: []
print(my_list)

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

13.Write a program to create, append, and remove


lists in python.
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the
key name.

Print the "brand" value of the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Output:
Ford

14.Write a program to demonstrate Sets, File


handling, exception handling in python.
Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Python File Open


File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify
them.

Open a File on the Server


Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the
content of the file:

Example
f = open("demofile.txt", "r")
print(f.read())
Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

If the file is located in a different location, you will have to specify the file path, like
this:

Example
Open a file on a different location:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Output:
Welcome to this text file!
This file is located in a folder named "myfiles", on the D drive.
Good Luck!

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Output:
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content!
Example
Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())
Output:
Woops! I have deleted the content!

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Result: a new empty file is created!

Example
Create a new file if it does not exist:

f = open("myfile.txt", "w")

Python Delete File


Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
Remove the file "demofile.txt":

import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to
delete it:

Example
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the os.rmdir() method:

Example
Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

Python Error Handling


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Output:
An exception occurred

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
This statement will raise an error, because x is not defined:

print(x)

NumPy Tutorial
NumPy is a Python library.

NumPy is used for working with arrays.

NumPy is short for "Numerical Python".

Example
Create a NumPy array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

15. Write a program to demonstrate Create a NumPy ndarray


Object in python.
NumPy is used to work with arrays. The array object in NumPy is
called ndarray.

We can create a NumPy ndarray object by using the array() function.

Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output:

[1 2 3 4 5]
<class 'numpy.ndarray'>

To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:

Example
Use a tuple to create a NumPy array:

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Output:

[1 2 3 4 5]
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).

nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D
array.

Example
Create a 0-D array with value 42

import numpy as np
arr = np.array(42)
print(arr)
Output:
42
1-D Arrays

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

These are the most common and basic arrays.

Example
Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

NumPy has a whole sub module dedicated towards matrix operations


called numpy.mat

Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
Output:
[[1 2 3]
[4 5 6]]

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.

Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values
1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

16. Write a program to demonstrate Numpy Array Indexing in


python.
Access Array Elements
Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0,
and the second has index 1 etc.

Get the first element from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[0])
Output:
1
Example
Get the second element from the following array.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[1])
Output:
2

Example
Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[2] + arr[3])
Output:
7

Access 2-D Arrays


To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.

Think of 2-D arrays like a table with rows and columns, where the dimension
represents the row and the index represents the column.

Example
Access the element on the first row, second column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])

Output:
2nd element on 1st dim: 2

Example
Access the element on the 2nd row, 5th column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd row: ', arr[1, 4])


Output:
5th element on 2nd dim: 10

Access 3-D Arrays


To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.

Example
Access the third element of the second array of the first array:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])
Output:
6

Example Explained
arr[0, 1, 2] prints the value 6.

And this is why:

The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]

The second number represents the second dimension, which also contains two
arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]

The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6

17.Write a program to demonstrate Numpy Array Reshaping


in python.Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in


each dimension.

Reshape From 1-D to 2-D


Example
Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)
Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Reshape From 1-D to 3-D


Example
Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with 2
elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

Output:
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]

Python Math
18.Write a program to demonstrate Math in python.
Python has a set of built-in math functions, including an extensive math module,
that allows you to perform mathematical tasks on numbers.

Built-in Math Functions


The min() and max() functions can be used to find the lowest or highest value in an
iterable:

Example
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)
Output:

5
25

The abs() function returns the absolute (positive) value of the specified number:

Example
x = abs(-7.25)

print(x)
Output:

7.25
y
The pow(x, y) function returns the value of x to the power of y (x ).

Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)

Output:

64

The Math Module


Python has also a built-in module called math, which extends the list of
mathematical functions.

To use it, you must import the math module:

import math

When you have imported the math module, you can start using methods and
constants of the module.

The math.sqrt() method for example, returns the square root of a number:

Example
import math

x = math.sqrt(64)

print(x)
Output:
8.0

The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer, and
returns the result:

Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1
Output:
2
1

The math.pi constant, returns the value of PI (3.14...):

Example
import math
x = math.pi

print(x)

19.Write a program to demonstrate Pandas Series in


python.

In Python, the pandas library is widely used for data


manipulation and analysis. A pandas Series is one-
dimensional labeled array capable of holding any
data type (integers, strings, floats, etc.). It is similar to
a column in a table or a list.

import pandas as pd

# Create a pandas Series with a list of data


data = [10, 20, 30, 40, 50]
series = pd.Series(data)

# Display the Series


print("Series:")
print(series)

# Create a Series with custom index


custom_index_series = pd.Series(data, index=['a', 'b', 'c', 'd', 'e'])
print("\nSeries with custom index:")
print(custom_index_series)

# Accessing elements of the Series


print("\nAccessing the first element:")
print(series[0])

print("\nAccessing an element using index:")


print(custom_index_series['c'])

# Perform arithmetic operations


print("\nAdd 5 to each element:")
print(series + 5)

print("\nMultiply each element by 2:")


print(series * 2)

# Perform basic statistics on the Series


print("\nMean of the Series:")
print(series.mean())

print("\nSum of the Series:")


print(series.sum())

# Check for conditions (boolean Series)


print("\nCheck if elements are greater than 25:")
print(series > 25)

Output:

Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64

Series with custom index:


a 10
b 20
c 30
d 40
e 50
dtype: int64

Accessing the first element:


10

Accessing an element using index:


30

Add 5 to each element:


0 15
1 25
2 35
3 45
4 55
dtype: int64

Multiply each element by 2:


0 20
1 40
2 60
3 80
4 100
dtype: int64

Mean of the Series:


30.0

Sum of the Series:


150

Check if elements are greater than 25:


0 False
1 False
2 True
3 True
4 True
dtype: bool

Explanation of Code:

1. Creating a Series:

o A pandas Series is created from a list, and it automatically gets a default


integer index (0, 1, 2, ...).

o You can also create a Series with custom indices, such as ['a', 'b', 'c', 'd',
'e'].

2. Accessing Data:

o You can access elements of the Series by using index positions or


custom labels (like series[0] or custom_index_series['c']).

3. Arithmetic Operations:

o Operations like addition (+) and multiplication (*) are element-wise, so


adding or multiplying a constant to a Series applies the operation to
each element individually.

4. Basic Statistics:

o You can use methods like .mean() and .sum() to calculate basic
statistics like the mean or sum of the Series.

5. Conditional Statements:

o You can check conditions on the Series to return a boolean result (like
whether elements are greater than 25).

20.Write a program to demonstrate Pandas Data


Frame in python.
This program demonstrates how to create a pandas DataFrame,
perform operations like adding columns, filtering data, calculating
statistics, and manipulating the DataFrame (e.g., dropping or
renaming columns). DataFrames are an essential part of data
analysis in Python using pandas.

import pandas as pd

# Create a DataFrame from a dictionary

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],

'Age': [24, 27, 22, 32, 29],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']

df = pd.DataFrame(data)

# Display the DataFrame

print("DataFrame:")

print(df)

# Access specific column

print("\nAccess 'Age' column:")

print(df['Age'])
# Access specific row by index

print("\nAccess first row by index:")

print(df.iloc[0])

# Access multiple rows by index

print("\nAccess first three rows:")

print(df.iloc[:3])

# Access a specific element (row, column)

print("\nAccess element in the second row and 'City' column:")

print(df.at[1, 'City'])

# Add a new column

df['Salary'] = [50000, 60000, 55000, 65000, 70000]

print("\nDataFrame after adding 'Salary' column:")

print(df)

# Perform operations on columns (e.g., adding 1000 to each salary)

df['Salary'] = df['Salary'] + 1000

print("\nDataFrame after increasing salary by 1000:")

print(df)
# Filter rows based on a condition (Age > 25)

print("\nRows where Age > 25:")

print(df[df['Age'] > 25])

# Basic statistics on DataFrame columns

print("\nBasic statistics for numerical columns:")

print(df.describe())

# Drop a column

df = df.drop('City', axis=1)

print("\nDataFrame after dropping the 'City' column:")

print(df)

# Rename columns

df = df.rename(columns={'Name': 'Full Name', 'Age': 'Age (Years)'})

print("\nDataFrame after renaming columns:")

print(df)

Output:
DataFrame:
Name Age City
0 Alice 24 New York
1 Bob 27 Los Angeles
2 Charlie 22 Chicago
3 David 32 Houston
4 Eve 29 Phoenix
Access 'Age' column:
0 24
1 27
2 22
3 32
4 29
Name: Age, dtype: int64

Access first row by index:


Name Alice
Age 24
City New York
Name: 0, dtype: object

Access first three rows:


Name Age City
0 Alice 24 New York
1 Bob 27 Los Angeles
2 Charlie 22 Chicago

Access element in the second row and 'City' column:


Los Angeles

DataFrame after adding 'Salary' column:


Name Age City Salary
0 Alice 24 New York 50000
1 Bob 27 Los Angeles 60000
2 Charlie 22 Chicago 55000
3 David 32 Houston 65000
4 Eve 29 Phoenix 70000
DataFrame after increasing salary by 1000:
Name Age City Salary
0 Alice 24 New York 51000
1 Bob 27 Los Angeles 61000
2 Charlie 22 Chicago 56000
3 David 32 Houston 66000
4 Eve 29 Phoenix 71000

Rows where Age > 25:


Name Age City Salary
1 Bob 27 Los Angeles 61000
3 David 32 Houston 66000
4 Eve 29 Phoenix 71000

Basic statistics for numerical columns:


Age Salary
count 5.000000 5.0
mean 26.400000 61000.0
std 3.737190 7983.0
min 22.000000 51000.0
25% 24.000000 56000.0
50% 27.000000 61000.0
75% 29.000000 66000.0
max 32.000000 71000.0

DataFrame after dropping the 'City' column:


Name Age Salary
0 Alice 24 51000
1 Bob 27 61000
2 Charlie 22 56000
3 David 32 66000
4 Eve 29 71000
DataFrame after renaming columns:
Full Name Age (Years) Salary
0 Alice 24 51000
1 Bob 27 61000
2 Charlie 22 56000
3 David 32 66000
4 Eve 29 71000

Explanation of the Code:


1. Creating a DataFrame:
o The pd.DataFrame() function is used to create a DataFrame from a
dictionary. The keys of the dictionary become the column labels,
and the values become the data in each column.
2. Accessing Data:
o You can access columns using the column name, e.g., df['Age'].
o You can access rows using iloc[] for integer-location based indexing
or loc[] for label-based indexing.
o To access a specific element, you can use at[] (for label-based
indexing) or iat[] (for position-based indexing).
3. Adding Columns:
o You can add new columns by assigning values to a new column
name, e.g., df['Salary'] = [50000, 60000, 55000, 65000, 70000].
4. Filtering Data:
o You can filter rows based on conditions, like df[df['Age'] > 25], which
selects rows where the 'Age' column is greater than 25.
5. Basic Statistics:
o The .describe() function provides summary statistics for the
numerical columns in the DataFrame.
6. Dropping Columns:
o The .drop() method is used to remove a column (or row) by
specifying the axis. In this case, we use axis=1 to drop a column.
7. Renaming Columns:
o The .rename() method allows you to rename columns. In this case,
we renamed 'Name' to 'Full Name' and 'Age' to 'Age (Years)'.

21.Write a program to demonstrate Data visualization


using Matplotlib and Seaborn.
Data visualization is a powerful tool in data analysis. In Python, matplotlib and
seaborn are two popular libraries used for creating various types of plots and
visualizations. matplotlib provides a flexible framework for plotting data, while
seaborn is built on top of matplotlib and provides a high-level interface for
creating attractive and informative statistical graphics.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Create a DataFrame with some sample data


data = {
'Age': [23, 25, 30, 35, 40, 45, 50, 55, 60, 65],
'Salary': [50000, 54000, 58000, 62000, 65000, 67000, 70000, 71000, 74000,
75000],
'Experience': [1, 2, 4, 6, 8, 10, 12, 14, 16, 18],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia',
'San Antonio', 'San Diego', 'Dallas', 'San Jose']
}

df = pd.DataFrame(data)

# Set Seaborn style


sns.set(style="whitegrid")

# 1. Line Plot using Matplotlib: Salary vs Experience


plt.figure(figsize=(8, 5))
plt.plot(df['Experience'], df['Salary'], marker='o', color='b', label='Salary vs
Experience')
plt.title('Salary vs Experience (Line Plot)', fontsize=14)
plt.xlabel('Experience (years)', fontsize=12)
plt.ylabel('Salary (USD)', fontsize=12)
plt.legend()
plt.grid(True)
plt.show()

# 2. Scatter Plot using Matplotlib: Age vs Salary


plt.figure(figsize=(8, 5))
plt.scatter(df['Age'], df['Salary'], color='g', label='Age vs Salary')
plt.title('Age vs Salary (Scatter Plot)', fontsize=14)
plt.xlabel('Age (years)', fontsize=12)
plt.ylabel('Salary (USD)', fontsize=12)
plt.legend()
plt.grid(True)
plt.show()

# 3. Histogram using Seaborn: Salary Distribution


plt.figure(figsize=(8, 5))
sns.histplot(df['Salary'], kde=True, color='purple', bins=10)
plt.title('Salary Distribution (Histogram)', fontsize=14)
plt.xlabel('Salary (USD)', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.show()

# 4. Box Plot using Seaborn: Salary Distribution by City


plt.figure(figsize=(8, 5))
sns.boxplot(x=df['City'], y=df['Salary'], palette='Set2')
plt.title('Salary Distribution by City (Box Plot)', fontsize=14)
plt.xlabel('City', fontsize=12)
plt.ylabel('Salary (USD)', fontsize=12)
plt.xticks(rotation=45)
plt.show()

# 5. Heatmap using Seaborn: Correlation Matrix


correlation_matrix = df[['Age', 'Salary', 'Experience']].corr()
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f',
linewidths=1)
plt.title('Correlation Heatmap', fontsize=14)
plt.show()

# 6. Pairplot using Seaborn: Pairwise Relationships


sns.pairplot(df[['Age', 'Salary', 'Experience']], hue='Age', palette='coolwarm')
plt.show()

Output Examples:
1. Line Plot (Salary vs Experience): A line graph showing how salary
increases with experience.
2. Scatter Plot (Age vs Salary): A scatter plot showing how age correlates
with salary.
3. Histogram (Salary Distribution): A histogram with a KDE curve showing
the distribution of salaries.
4. Box Plot (Salary by City): A box plot showing salary distribution for
different cities.
5. Correlation Heatmap: A heatmap showing how strongly the variables
Age, Salary, and Experience are correlated.
6. Pairplot: A grid of scatter plots that shows relationships between
multiple pairs of columns.

Explanation of the Code:


1. Matplotlib Line Plot:
o We create a line plot to visualize the relationship between
Experience and Salary. We use the plot() function, and customize
the plot with a title, labels, and a grid.
2. Matplotlib Scatter Plot:
o A scatter plot is created to show the relationship between Age and
Salary. The scatter() function is used, and similar customization is
applied as in the line plot.
3. Seaborn Histogram:
o Using sns.histplot(), we create a histogram of the Salary column.
We also add a Kernel Density Estimate (KDE) to show the
probability distribution. The bins parameter controls the number
of bins.
4. Seaborn Box Plot:
o A box plot is used to visualize the distribution of Salary across
different cities. The sns.boxplot() function is used, and the plot is
customized with labels and colors.
5. Seaborn Heatmap:
o A heatmap is created to show the correlation matrix between the
Age, Salary, and Experience columns. The sns.heatmap() function
is used, and we annotate the heatmap with correlation values.
6. Seaborn Pairplot:
o A pairplot is a useful way to visualize pairwise relationships
between several variables. We use sns.pairplot() to plot
relationships between Age, Salary, and Experience. The hue
parameter adds color to distinguish the variables.
22.Write a program to demonstrate Plotting line
charts using Matplotlib and Seaborn.

import matplotlib.pyplot as plt

# Sample data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
sales = [2300, 2500, 2700, 3000, 3500, 4000, 4500, 4800, 5000, 5500, 6000,
6500]

# Create a line chart


plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o', color='b', linestyle='-', linewidth=2,
markersize=8)

# Add titles and labels


plt.title('Monthly Sales for 2024', fontsize=16)
plt.xlabel('Months', fontsize=12)
plt.ylabel('Sales (USD)', fontsize=12)

# Add gridlines for better readability


plt.grid(True)

# Display the line chart


plt.show()

Output:
This code will generate a line chart showing the monthly sales from January to
December. The chart will have the following features:
● The months will be plotted on the x-axis.
● The sales figures will be plotted on the y-axis.
● A solid blue line connects the data points for each month, with circular
markers at each point.
● A title and axis labels will be displayed to clarify what the chart
represents.

Explanation of the Code:


1. Data Preparation:
o months: A list of months in a year (January to December).
o sales: A list representing the sales figures for each corresponding
month.
2. Line Plot Creation:
o plt.plot(): This function is used to create a line plot. The parameters
used are:
● months: The x-axis data.
● sales: The y-axis data.
● marker='o': Adds circular markers at each data point on the
line.
● color='b': Sets the color of the line (blue in this case).
● linestyle='-': Specifies that the line should be solid.
● linewidth=2: Makes the line thicker.
● markersize=8: Sets the size of the markers.
3. Adding Titles and Labels:
o plt.title(): Sets the title of the plot.
o plt.xlabel(): Labels the x-axis (months).
o plt.ylabel(): Labels the y-axis (sales in USD).
4. Gridlines:
o plt.grid(True): Enables gridlines on the plot, which makes it easier to
read the values.
5. Displaying the Plot:
o plt.show(): This function is used to display the plot.
23.Write a program to demonstrate Plotting bar
charts using Matplotlib and Seaborn.

1. Bar Chart using Matplotlib


Matplotlib provides the bar() function to create bar charts. Here's an
example program that shows how to plot a bar chart using Matplotlib.
Example: Bar Chart with Matplotlib
python

Copy code

import matplotlib.pyplot as plt

# Sample data

categories = ['A', 'B', 'C', 'D', 'E']

values = [10, 15, 7, 25, 30]

# Create a bar chart

plt.figure(figsize=(8, 5))

plt.bar(categories, values, color='skyblue')

# Add titles and labels

plt.title('Category vs Value (Bar Chart)', fontsize=16)

plt.xlabel('Category', fontsize=12)

plt.ylabel('Value', fontsize=12)

# Display the chart


plt.show()

Explanation:
1. Data Preparation:
o categories: A list of category names.
o values: A list of values corresponding to each category.
2. Bar Chart Creation:
o plt.bar(categories, values, color='skyblue'): This creates the bar
chart with categories on the x-axis and values on the y-axis. The
color of the bars is set to sky blue.
3. Titles and Labels:
o The title and axis labels are added using plt.title(), plt.xlabel(), and
plt.ylabel().
4. Displaying the Chart:
o plt.show(): This displays the bar chart.
Output:
This will generate a simple bar chart with categories on the x-axis and
corresponding values on the y-axis.

2. Bar Chart using Seaborn


Seaborn is built on top of Matplotlib and provides a high-level interface
for creating more complex and aesthetically pleasing charts. For bar
charts, Seaborn offers the barplot() function.
Example: Bar Chart with Seaborn
python

Copy code

import seaborn as sns

import matplotlib.pyplot as plt

# Sample data
data = {

'Category': ['A', 'B', 'C', 'D', 'E'],

'Value': [10, 15, 7, 25, 30]

# Create a DataFrame from the data

import pandas as pd

df = pd.DataFrame(data)

# Create a bar chart using Seaborn

plt.figure(figsize=(8, 5))

sns.barplot(x='Category', y='Value', data=df, palette='viridis')

# Add titles and labels

plt.title('Category vs Value (Seaborn Bar Chart)', fontsize=16)

plt.xlabel('Category', fontsize=12)

plt.ylabel('Value', fontsize=12)

# Display the chart

plt.show()

Explanation:
1. Data Preparation:
o We create a Pandas DataFrame df from a dictionary. The dictionary
contains Category names and their corresponding Value.
2. Bar Chart Creation with Seaborn:
o sns.barplot(x='Category', y='Value', data=df, palette='viridis'): This
creates the bar chart using the barplot() function, where
x='Category' and y='Value' refer to the columns of the DataFrame.
The palette parameter is used to define the color palette for the
bars.
3. Titles and Labels:
o Just like with Matplotlib, we add the title and axis labels using
plt.title(), plt.xlabel(), and plt.ylabel().
4. Displaying the Chart:
o plt.show() is used to display the Seaborn-generated bar chart.
Output:
This will generate a bar chart similar to the one created with Matplotlib,
but with Seaborn’s built-in color palette and additional styling options.

Key Differences Between Matplotlib and Seaborn for Bar Charts:


● Matplotlib:
o More control and flexibility over customization.
o Requires manually setting up the data.
o You need to use plt.bar() for creating bar charts.
● Seaborn:
o Provides higher-level abstraction with automatic formatting.
o Simpler syntax when working with Pandas DataFrames.
o Uses sns.barplot() to plot bar charts, which also calculates
statistics like mean by default.

24. Write a program to demonstrate Plotting pie charts


using Matplotlib and Seaborn.

Pie charts are useful for visualizing the proportions of different


categories in a dataset. In Python, you can easily plot pie charts using
Matplotlib. Seaborn does not have a direct function for pie charts, as it
focuses on statistical graphics, but you can use Matplotlib directly to
create pie charts while using Seaborn for styling.

1. Pie Chart using Matplotlib


Matplotlib provides a function plt.pie() to create pie charts. Here's an
example:
Example: Pie Chart with Matplotlib
python

Copy code

import matplotlib.pyplot as plt

# Data for the pie chart

categories = ['A', 'B', 'C', 'D', 'E']

values = [10, 15, 25, 30, 20]

# Create a pie chart

plt.figure(figsize=(8, 8))

plt.pie(values, labels=categories, autopct='%1.1f%%', startangle=140,


colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'])

# Add a title

plt.title('Category Distribution (Pie Chart)', fontsize=16)

# Display the pie chart

plt.show()
Explanation:
1. Data Preparation:
o categories: A list of categories or labels.
o values: A list of corresponding values for each category.
2. Creating the Pie Chart:
o plt.pie(values, labels=categories, autopct='%1.1f%%',
startangle=140): This function creates the pie chart.
● values: The data for each category (the size of each slice).
● labels: The labels for each slice.
● autopct='%1.1f%%': This formats the percentage of each slice with
one decimal point.
● startangle=140: This rotates the start angle of the pie chart to 140
degrees for better readability.
● colors: Specifies the color for each slice.
3. Title:
o The title of the chart is set using plt.title().
4. Displaying the Chart:
o plt.show() is used to display the pie chart.
Output:
This will generate a pie chart that shows the distribution of values
across the categories, with each slice labeled by its percentage.

2. Pie Chart using Matplotlib with Seaborn Styling


While Seaborn doesn't have a built-in function for pie charts, you can use
Seaborn's styling to make the chart look more aesthetically pleasing. You
can use sns.set() to set the Seaborn style before creating the pie chart.
Example: Pie Chart with Seaborn Styling
python

Copy code

import matplotlib.pyplot as plt


import seaborn as sns

# Data for the pie chart

categories = ['A', 'B', 'C', 'D', 'E']

values = [10, 15, 25, 30, 20]

# Apply Seaborn style

sns.set(style="whitegrid")

# Create a pie chart

plt.figure(figsize=(8, 8))

plt.pie(values, labels=categories, autopct='%1.1f%%', startangle=140,


colors=sns.color_palette("Set2", len(values)))

# Add a title

plt.title('Category Distribution (Pie Chart with Seaborn Style)',


fontsize=16)

# Display the pie chart

plt.show()

Explanation:
1. Seaborn Styling:
o sns.set(style="whitegrid"): This applies Seaborn's whitegrid style,
which adds a light grid to the background and improves the overall
appearance.
2. Color Palette:
o colors=sns.color_palette("Set2", len(values)): This uses Seaborn's
built-in color palette Set2, which provides a set of attractive,
distinct colors for the pie chart slices.
3. Rest of the Chart Creation:
o The rest of the chart creation process is identical to the previous
Matplotlib example.
Output:
This will generate a pie chart similar to the previous one, but with
Seaborn's color palette and grid style, making the chart look more
polished.

24.Write a program to demonstrate scatter plots


using Matplotlib and Seaborn.

Scatter plots are an excellent way to visualize the relationship between


two continuous variables. Both Matplotlib and Seaborn can be used to
create scatter plots, with Seaborn providing additional functionality for
statistical insights and easier styling.
1. Scatter Plot using Matplotlib
Matplotlib provides the scatter() function to create scatter plots. Here's
an example program:
Example: Scatter Plot with Matplotlib
python

Copy code

import matplotlib.pyplot as plt

# Sample data

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Create a scatter plot

plt.figure(figsize=(8, 5))

plt.scatter(x, y, color='blue', marker='o', s=100, edgecolors='black')

# Add titles and labels

plt.title('Scatter Plot of x vs y', fontsize=16)

plt.xlabel('x', fontsize=12)

plt.ylabel('y', fontsize=12)

# Display the plot

plt.grid(True)

plt.show()

Explanation:
1. Data Preparation:
o x and y represent the x-axis and y-axis data points.
o In this example, the relationship between x and y is quadratic (i.e.,
y=x2y = x^2y=x2).
2. Scatter Plot Creation:
o plt.scatter(x, y): This creates the scatter plot where x and y are the
data points.
o color='blue': The color of the scatter points.
o marker='o': The shape of the points (circles in this case).
o s=100: The size of each scatter point (100 pixels).
o edgecolors='black': The color of the edges around each point.
3. Adding Titles and Labels:
o plt.title(), plt.xlabel(), and plt.ylabel() are used to add the title and
axis labels.
4. Displaying the Plot:
o plt.show() displays the plot.
o plt.grid(True) adds a grid to the plot for better readability.
Output:
This will display a scatter plot of the data points with a quadratic
relationship between x and y.

2. Scatter Plot using Seaborn


Seaborn builds on Matplotlib and offers additional features like color-
coding based on a third variable or automatic regression lines. Here's
how to create a scatter plot with Seaborn:
Example: Scatter Plot with Seaborn
python

Copy code

import seaborn as sns

import matplotlib.pyplot as plt

# Sample data

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

y = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Create a DataFrame for Seaborn

import pandas as pd

df = pd.DataFrame({'x': x, 'y': y})


# Create a scatter plot using Seaborn

plt.figure(figsize=(8, 5))

sns.scatterplot(data=df, x='x', y='y', color='green', marker='o', s=100)

# Add titles and labels

plt.title('Scatter Plot of x vs y (Seaborn)', fontsize=16)

plt.xlabel('x', fontsize=12)

plt.ylabel('y', fontsize=12)

# Display the plot

plt.show()

Explanation:
1. Data Preparation:
o A Pandas DataFrame df is created to hold the data, which is
required by Seaborn for plotting.
2. Scatter Plot Creation:
o sns.scatterplot(data=df, x='x', y='y'): This creates the scatter plot
using Seaborn's scatterplot() function. The data argument is the
DataFrame, and x and y specify the columns to plot.
o color='green': The color of the scatter points.
o marker='o': The shape of the points (circles).
o s=100: The size of each scatter point.
3. Adding Titles and Labels:
o Just like with Matplotlib, plt.title(), plt.xlabel(), and plt.ylabel() are
used to set the title and labels.
4. Displaying the Plot:
o plt.show() is used to display the plot.
Output:

You might also like