DVTP LAB Manual R21 IT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

VARDHAMAN COLLEGE OF ENGINEERING, HYDERABAD

(Autonomous)
NAAC-A Grade, NBA Accredited: Affiliated to JNTUH, Hyderabad
ISO 9001:2008 Certified.
DEPARTMENT OF INFORMATION TECHNOLOGY

Laboratory Manual
of
DATA VISUALIZATION THROUGH PYTHON
(I B.Tech- II SEMESTER)
(VCE-R21)
Course Title DATA VISUALIZATION THROUGH PYTHON Course Type Integrated
I Year II
Course Code A7601 Credits Class
Semester
Contact Work Total Number of
TLP Credits Assessment in
Hours Load Classes
Weight age
Theory 1 1 1 Per Semester
Course
Structure Practice 2 4 4
Theory Practical CIE SEE
- - - -
Total 3 5 5 1 4 30 70
Course Lead: Dr Muni Sekhar Velpuru
Theory Practice
Course
IT IT
Instructors
 Dr Muni Sekhar Velpuru  Dr Muni Sekhar Velpuru
 Mr Anudeep M  Mr Anudeep M

Duration Component Wise Total


Component Weightage Marks
in Hours Marks Marks

Theory: Test-1 1 20
Continuous
Theory: Test-2 1 20
Internal 100 0.3 30
Evaluation (CIE) Alternate
- 20
Assessment*
Practical Exam 2 40

Semester End Exam (SEE) 3 100 100 0.7 70

Total 100

COURSE DESCRIPTION:
This course is all about addressing today’s data driven world, in visualizing the data graphically.
Though its foundations are rooted in statistics, many advanced fields of science are practicing it to
explore their large volumes of data and to throw deeper insights of the data. The main aim of this
course is to give better understandings of data and making sense of hidden information using the
basic programming methodology in Python. Visualizing enormous data using graphics can run all
possible unknown stories about data. Data visualization skills learned through this course may raise
the student creativity in presenting projects he encountered. The course uses some of the open
source data Visualization tools.

COURSE OUTCOMES:
At the end of the course student will be able to:
 A7601.1 Identify the various building blocks to write a Python program.
 A7601.2 Use control statements and build defined functions for solving a given problem by
improving code re-usability.
 A7601.3 Implement fundamental data structures for manipulating data.
 A7601.4 Implement various visualizations using advanced libraries.
 A7601.5 Design suitable visualizations for the given data and infer data insights.

BLOOM’S LEVEL OF THE COURSE OUTCOMES

Bloom’s Level
CO# Remember Understand Apply Analyze Evaluate Create
(L1) (L2) (L3) (L4) (L5) (L6)
A7601.1 √
A7601.2 √
A7601.3 √
A7601.4 √
A7601.5 √
COURSE ARTICULATION MATRIX

PO10

PO11

PO12

PSO1

PSO2
CO#/
PO1
PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9
Pos

A7601.1 3 2 2
A7601.2 3 2 2
A7601.3
2 3 3 3
A7601.4 3 1 1
A7601.5 2 2 2 1 1

Note: 1-Low, 2-Medium, 3-High

COURSE PREREQUISITES:
 Problems Solving
Programs
Week 1:

Introduction to Python Lab –Input Output Statements, Variables and Expressions


(a) Write a python program to read integer, float & string values and display themon
the screen.
(b) Write a python program to read a float value and convert Fahrenheit to Centigrade.
(c) Write a python program to find the area of triangle.
(d) Write a python program to read the Marks in4 Subjects and Display the average.

Week 2:
Programs using various operators in Python
a) Write a python program to swap / interchange two numbers with third variableand
without using third variable.
b) Write a program that asks the user for a number of seconds and prints outhow
many minutes and seconds in it. For instance, 200 seconds is 3minutes and20seconds.
c) Write a python program for demonstrating the usage of comparison, unary, shift, logical,
membership and identity operators.
Week 3:
Programs using Conditional Statements & Iterative Statements
(a) Write a python program to check a given number is Even or Odd.
(b) Write a python program to demonstrate nested if and nested if-else to find the
greatest of 3 integer numbers
(c) Write a Python program to find the factorial of a given number.
(d) Write a Python program to reverse the digits of a given number.
(e) Write a python program to display all prime numbers between 0 to n.
(f) Write a program to print all Armstrong numbers between given range using forloop.
(g) Write a Python program to display a simple pyramid pattern for demonstratingnested
loop.
Week 4:
Programs using Strings and Its Operations
(a) Write a program that asks the user to enter a string and perform the following:
i. The total number of characters in the string.
ii. Repeat the string 10 times.
iii. The first character of the string.
iv. The first three characters of the string.
v. The last three characters of the string
vi. The string in backwards.
vii. The seventh character of the string if exist otherwise display a message “Not
exist”.
viii. The string with its first and last characters removed.
ix. The string into capital case
x. The string with every a replaced with ane.
xi. The string with every letter replaced by a space.
(b) Write a python program to read a string and find the number of characters in it.
(Without using Built in Functions).
(c) Write a Python program to read a String and check whether the string is
palindrome or not. (Without using Built in Functions).

Week 5:
Programs using Python Data Structures (Lists).
(e) Write a python program to perform following operations on a list of integers.
i. Write a program that asks the user to enter a string and perform the following:
ii. Print the last item in the list.
iii. Print the list in reverse order.
iv. Print Yes if the list contains a 5 and No otherwise.
v. Print the number of occurrences of a element in the list.
vi. Remove the first and last items from the list and sort the remaining items.
vii. Print how many integers in the list is less than a given value?
viii. Print the average of the elements in the list.
ix. Print the largest and smallest value in the list.
x. Print the second largest and second smallest entries in the list.
xi. Print number of even numbers in the list.
Week 6:
Programs using Python Data Structures (Dictionary).
(a) Write a python program for demonstrating the creation of dictionary, accessing
dictionary elements, modifying dictionary elements, finding length and possible
operations.
(b) Write a python program to create a dictionary of students with keys as roll num-
bers and values as names. Perform operations like insert, update and modify
student data.
(c) Write a program that uses a dictionary that contains ten user names and pass-
words. The program should ask the user to enter username and password. If the
username is not in the dictionary, the program should indicate that the person is “not
a valid user” of the system. If the username is in the dictionary, but the userdoes
not enter the right password, the program should say that “the password is invalid”.
If the password is correct, then the program should display “Welcome”.

Week 7:
Programs using Python Data Structures (Tuples and Set)
a) Write a python program to demonstrate various operations on tuples.
b) Write a python program to demonstrate various operations onsets.

Week 8:
Programs using User Defined Functions.
(a) Write a Python program to calculate simple interest using function
(b) Write a Python program to find the nth term of a Fibonacci number using function.
(c) Write a Python program to find the number of elements in a list using function.
(d) Write a python program to find factorial of a given number using recursion.
(e) Write a python program to find sum of individual digits of a given number using
recursion
Week 9:
Programs using Bar charts and Pie charts.
a) Write a python program to visualize bar and column chart for a given data includes
months on x-axis and prices on y-axis.
b) Write a python program to visualize plot bar charts and histograms for a given 30
students averages.
c) The table given shows the sales of books (in thousand number) from six branchesof
a publishing company during two consecutive years 2000 and 2001.
i. Write a python to display bar graphs of the sales and use different color
foreach bar
ii. Write a python to visualize the percentage of sales using pie chars.

Years B1 B2 B3 B4 B5 B6
2020 80 75 98 83 75 72
2021 105 68 107 95 95 80

Week 10:
Programs using Visualization.
(a) Jerry recorded the temperature in his room (in Degrees Fahrenheit) every two hours
over a 12 hour period from noon to midnight, as Temp=40, 42,45,46,38,36,34. Write a
Python program to visualize the recorded temperatures as line graph.
(b) The population (in thousands) of a town was recorded every twenty years from
1900 to 2000. Population =3, 4,2,5,7,7,7. Write a program to visualize a line graph
by taking years on x-axis.
Week 11:
Programs using Datasets.
a. You are required to construct two datasets with the GPA of two classes each of
60 students.
i. Write a Python program to compare the GPA distribution of each using a
suitable Visualization approach and what can you infer from the distributions.
ii. Write a program to display Boxplot analysis for the same.
b. Write a python program to implement the following on iris data set
i. Visualize the petal length, petal width, sepal length, sepal width.
ii. Visualize average of each.
What can you infer from the visualization? Throw the major insights youhave observed from
the visualizations

Week 12:
Programs using Heat Maps.
a) Write a program to visualize the correlations between various numeric features of
iris data using heat maps.
b) Write a python program to visualize the correlations between various numeric
features of the Titanic data and analyze which features are more important.

Week 13:
Programs using Seaborn.
a) Write a python program to create violin plots of iris species using seaborn

Practice:
1. Implement a program in python to demonstrate the usage of python variables, data
types, operators and I/O
2. Implementing python Decision making and Looping constructs
3. Implementing python data types like lists and tuples.
4. Programs on python string manipulation operations
5. Programs on implementing set and dictionary data types in python
6. Programs on implementing functions and recursion in functions using python
7. Programs on implementing file operations in python

TEXT BOOKS
T1. ReemaThareja. Python Programming using Problem solving Approach. Oxford University
Press, New Delhi India, 2017.
T2. Bajaj Chandrajit, "Data Visualization Techniques", John willey and sons.
T3. Dr.Ossama Embark,"Data Analysis and Visualization using Python", Apress.

REFERENCE BOOKS:
R1. Timothy A Budd. Exploring Python. Tata McGraw Hill Education Private Limited.New
Delhi India, 2008.
R2. Mark Lutz. Learning Python. 5th Edition. O’Reilly, USA, 2015.
R3. Brian Heinold. A Practical Introduction to Python Programming, 2012.
R4. Anthony Banfield, "Thinking Statistically".

Online Tutorials:

http://www.nptel.com
http://www.learnpython.org/
https://docs.python.org/2/tutorial/index.html
http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Intro
https://newprediction.com/free-data-visualization-books/
https://www.kaggle.com/learn/data-visualization
https://www.kaggle.com/sanikamal/data-visualization-using-matplotlib
http://www.pythontutor.com/
https://www.datacamp.com/courses/intro-to-python-for-data-science
ASSESSMENT SCHEME

Vardhaman College of Engineering Data Visualization through Python


1(a)Write a python program to read integer, float & string values and display them on the
screen.

a=int(input("Enter any integer value"))


b=float(input("Enter any float value"))
c=input("Enter a string")

print(" Integer a=",a,"\n Float b=",b,"\n String c=",c)

Output:

1(b)Write a python program to read a float value and convert Fahrenheit to Centigrade.

Celsius = float(input("Temperature value in degree Celsius: " ))


# For Converting the temperature to degree Fahrenheit
Fahrenheit = (Celsius * 1.8) + 32
# print the result
print('The %.2f degree Celsius is equal to: %.2f Fahrenheit' %(Celsius, Fahrenheit))

Output:

1(c)Write a python program to find the area of triangle.


# Three sides of the triangle is a, b and c:

a = float(input('Enter first side: '))


b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print("The area of the triangle is %0.2f" %area)
#print("The area of the triangle is =", round(area,2))

Output:

Vardhaman College of Engineering Data Visualization through Python


1(d)Write a python program to read the Marks in 4 Subjects and Display the average
sub1 = float(input('Enter first subject marks : '))
sub2 = float(input('Enter second subject marks: '))
sub3 = float(input('Enter third subject marks: '))
sub4 = float(input('Enter forth subject marks: '))
Avg=(sub1+sub2+sub3+sub4)/4
print("The Average Marks =",Avg)

Output:

2(a)Write a python program to swap / interchange two numbers with third variable and
without using third variable.
# To take inputs from the user

x = input('Enter First Value to be Swaped: ')


y = input('Enter Second Value to be Swaped: ')

#create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The First Value after swapping: {}'.format(x))


print('The Second Value after swapping: {}'.format(y))

#Second Method for Swaping without 3rd variable


#(x,y)=(y,x)
#print('The First Value after swapping: {}'.format(x))
#print('The Second Value after swapping: {}'.format(y))

#Another Method for Swaping without 3rd variable


#x=x+y
#y=x-y
#x=x-y
#print('The First Value after swapping: {}'.format(x))
#print('The Second Value after swapping: {}'.format(y))

Vardhaman College of Engineering Data Visualization through Python


Output:

2{b}Write a program that asks the user for a number of seconds and prints out
how many minutes and seconds in it. For instance, 200 seconds is 3minutes
and20seconds

seconds=int(input ("enter seconds:"))


min=seconds//60
hours=seconds//3600
seconds=seconds%60

if hours>=1:
print(hours,"Hours", min-60*hours,"minutes",seconds,"seconds")
else:
print(min,"minutes",seconds,"seconds")

Output:

2(c)Write a python program for demonstrating the usage of comparison, unary, shift,
logical, membership and identity operators.

a = int(input("Enter vaue : "))


b = int(input("Enter vaue : "))

#Arithmetic Operators
print("Addition =",a + b)
print("Subtraction =",a - b)
print("Multiplication =",a * b)
print("Division =",a / b)
print("Floor Division =",a // b)
print("Modilus =",a % b)

#Comparison Operators
print("is a > b :",a > b)
print("is a < b :",a < b)
print("is a == b :",a == b)
print("is a != b :",a != b)
print("is a >= b :",a >= b)
print("is a <= b :",a <= b)

Vardhaman College of Engineering Data Visualization through Python


#Logical Operators
x = True
y = False
print("True and False =",x and y)
print("True or False =",x or y)
print("not False =",not y)

#Bitwise Operators
print(f"Bitwise AND of {a}, {b} =",a & b)
print(f"Bitwise OR of {a}, {b} =",a | b)
print(f"Bitwise NOT of {a} =",~a)
print(f"Bitwise XOR of {a}, {b} =",a ^ b)
print(f"Bitwise Right shift of {a} =",a >> 2)
print(f"Bitwise Left shift of {a} =",a << 2)

#Identity Operator
print("if the operands are not identical ",a is not b)
print("if the operands are identical ",a is b)
list = [10, 20, 30, 40, 50]
if (a not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (b in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output:

Vardhaman College of Engineering Data Visualization through Python


3(a)Write a python program to check a given number is Even or Odd

n=int(input("Enter a value : "))


#if-else statement
if n%2 == 0 :
print("Given number %d is even " %n)
else:
print("Given number %d is odd "%n)

Output:

3(b) Write a python program to demonstrate nested if and nested if-else to find the greatest of
3 integer numbers

a = int(input("Enter 1st vaue : "))


b = int(input("Enter 2nd vaue : "))
c = int(input("Enter 3rd vaue : "))
if a>b:
Vardhaman College of Engineering Data Visualization through Python
if a>c:
print("%d is the greatest of given 3 numbers"%a)
else:
print("%d is the greatest of given 3 numbers"%c)
else:
if b>c:
print("%d is the greatest of given 3 numbers"%b)
else:
print("%d is the greatest of given 3 numbers"%c)

Output:

3(c)Write a Python program to find the factorial of a given number.

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:

3(d) Write a Python program to reverse the digits of a given number.

Number = int(input("Please Enter any Number: "))


Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10

print("\n Reverse of entered number is = %d" %Reverse)

Output:

Vardhaman College of Engineering Data Visualization through Python


3(e)Write a python program to display all prime numbers between min to max

minm = int(input("Enter the min : "))


maxm = int(input("Enter the max : "))
for n in range(minm,maxm + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n, end=' ')

Output:

3(f)Write a python program to display all Armstrong numbers between min to max

minm = int(input("Enter the min : "))


maxm = int(input("Enter the max : "))
print(f'The Armstrong numbers between {minm} and {maxm} are =')
for num in range(minm, maxm + 1):
# order of number
order = len(str(num))
# initialize sum
total = 0
temp = num
while temp > 0:
digit = temp % 10
total = total + digit ** order
temp = temp // 10
if num == total:
print(num)

Output:

Vardhaman College of Engineering Data Visualization through Python


3(g) Write a Python program to display a simple pyramid pattern for demonstrating nested
loop.

n=int(input("Enter the range to be printed :"))


k=n-1
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k=k-1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print()

Output:

4(a) Write a program that asks the user to enter a string and perform the following:

string=input("Enter the string")

# i. The total number of characters in the string.


print("Length of String",len(string))

Output:
Enter the stringStudents of R21 Batch
Length of String 21

# ii. Repeat the string 10 times.


print("Repitetion "<string*10)

Output:

Vardhaman College of Engineering Data Visualization through Python


Repitetion Students of R21 BatchStudents of R21 BatchStudents of R21 BatchStudents of R21
BatchStudents of R21 BatchStudents of R21 BatchStudents of R21 BatchStudents of R21
BatchStudents of R21 BatchStudents of R21 Batch

# iii. The first character of the string.


print("first character =",string[0])

Output:
first character = S

# iv. The first three characters of the string.


print("first three character =",string[0:4])

Output:
first three character = Stud

# v. The last three characters of the string


print("last three character =",string[-3:])

Output:
last three character = tch

# vi. The string in backwards.


print('The string in backwards',string[-1:0:-1])

Output:
The string in backwards hctaB 12R fo stnedut

# vii. The seventh character of the string if exist otherwise display a message “Not exist”
if len(string)>=7:
print('seventh character =',string[6])
else:
print("value does Not exist")

Output:
seventh character = t

# viii. The string with its first and last characters removed.
print('string with its first and last characters removed.',string[1:-1])

Output:
string with its first and last characters removed. tudents of R21 Batc

# ix. The string into capital case


print('string into capital case ',string.upper())

Output:
string into capital case STUDENTS OF R21 BATCH

Vardhaman College of Engineering Data Visualization through Python


# x. The string with every a replaced with ane
print('string with every a replaced with ane ',string.replace('a','ane'))

Output:
string with every a replaced with ane Students of R21 Banetch

# xi. The string with every letter replaced by a space.


import re #regular Expretion
s1=re.sub(r"[^0-9 ]"," ",string)
print('string with every letter replaced by a space',s1)

Output:
string with every letter replaced by a space 21

4(b)Write a python program to read a string and find the number of characters in it. (Without
using Built in Functions).

s = input("Enter the string :")


d=list(s.split())
char,wrd=0,0
for i in s:
char=char+1
for j in d:
wrd=wrd+1
print(f"Total no of Charecters are = {char} and total no of words = {wrd}")

Output:

4(c)Write a Python program to read a String and check whether the string is palindrome or not.
#(Without using Built in Functions).

s = input("Enter the string :")


if s == s[-1::-1]:
print(f"given string {s} is palindrome")
else:
print("Not a Palindrome")

Output:

5. Programs using Python Data Structures (Lists)


5(a)Write a python program to perform following operations on a list of integers.

Vardhaman College of Engineering Data Visualization through Python


# i. Write a program that asks the user to enter a string and perform the following:
n=int(input("Please enter the list length "))
ls=[]
for i in range (0,n):
print("Entering element ",i)
list_item=int(input("Please enter the element "))
ls.append(list_item)
print(ls)

Output:

ii. Print the last item in the list.

print("The last item in list =",ls[-1])

Output:

# iii. Print the list in reverse order.

print("The list in reverse order =",ls[-1::-1])

Output:

# iv. Print Yes if the list contains a 5 and No otherwise.

var=int(input("enter the element you want to find in list : "))

Vardhaman College of Engineering Data Visualization through Python


if var in ls:
print(f"YES, {var} element found in list at index {ls.index(var)}")
else:
print(f"NO, {var} item not found")

Output:

# v. Print the number of occurrences of an element in the list.

ser=int(input("enter the element you want to find in list : "))


print(f"Element {ser} found ",ls.count(ser),"no of times")

Output:

# vi. Remove the first and last items from the list and sort the remaining items.

_,*mid,_=ls
#mid=ls[1:-1]
print("list before removing first and last items ",ls)
print("list before sorting ",mid)
mid.sort()
print("sorted list after removing first and last items ",mid)

Output:

# vii. Print how many integers in the list is less than a given value?

fnd=int(input("Enter value to compare : "))


count = 0
for i in ls :
if i < fnd :
count = count + 1
print (f"The numbers of values less than {fnd} are = {count}")

Output:

Vardhaman College of Engineering Data Visualization through Python


# viii. Print the average of the elements in the list.

total = 0
# Finding the sum sum(ls)
for i in ls:
total += i
# divide the total elements by number of elements
avg = total/len(ls)
print("sum = ", total)
print("average = ", avg)

Output:

# ix. Print the largest and smallest value in the list.

print("the original list =",ls)


print(f"The largest in the list = {max(ls)} and \nsmallest in the list = {min(ls)}")
#Another method -> ls.sort();print("largest =",ls[-1],"Smallest =",ls[0])

Output:

# x. Print the second largest and second smallest entries in the list.

largest = ls[0]
lowest = ls[0]
largest2 = None
lowest2 = None
for item in ls[1:]:
if item > largest:
largest2 = largest
largest = item
elif largest2 is None or largest2 < item:
largest2 = item
if item < lowest:
lowest2 = lowest
lowest = item
elif lowest2 is None or lowest2 > item:
lowest2 = item
print("Largest element is:", largest)
print("Smallest element is:", lowest)
print("Second Largest element is:", largest2)

Vardhaman College of Engineering Data Visualization through Python


print("Second Smallest element is:", lowest2)

'''Anoher method
#second largest
for i in l1[::-1]:
if(max(l1)>i):
print(i)
break
#second min
for i in l1:
if(min(l1)<i):
print(i)
break'''

Output:

#xi. Print number of even numbers in the list.

c=0
for evn in ls:
# check
if evn % 2 == 0:
c=c+1
print(evn, end = " ")
print("Total no of Even numbers =",c)

Output:

6. Programs using Python Data Structures (Dictionary).


(a) Write a python program for demonstrating the creation of dictionary, accessing dictionary
elements,
#modifying dictionary elements, finding length and possible operations

Dc1 = {}
n=int(input('enter range'))
Dc1[1] = 'Vardhaman'
for i in range(2,n):
v=input(f'enter {i} value ')
Dc1[i]=v
print(Dc1)

Vardhaman College of Engineering Data Visualization through Python


Dc2 = {4: 'mid', 5: 'next', 6: 'last'}
Dc1.update(Dc2)

print('len =',len(Dc1))
print('min = ',min(Dc1))
print('max = ',max(Dc1))
print('sum = ',sum(Dc1))
print(Dc1.values())
print(Dc1.keys())
print(Dc1.items())
print(Dc1.get(3))
print(Dc1)

Output:

(b) Write a python program to create a dictionary of students with keys as roll numbers and
values as names. Perform operations like insert, update and modify student data

m=int(input("Enter no of students to be entered "))


student={}
for i in range(m):
rollno=input("Enter Rollno ")
name=input("Enter Name ")
student[rollno]=name #inserting into dictionary
print(student)

# Perform operations like insert, update and modify student data


print("the existing dictionary is = ",student)
Vardhaman College of Engineering Data Visualization through Python
delet= input("enter the key you want to delete")

print(student.pop(delet)) #deleting from dictionary

mod= input("enter the key you want to modify")


student[mod]=input("enter the value to the key") #modifying the dictionary

print('After Insertion and deletion',student)

stud_le={'1205':'guna','1206':'ravi','1207':'madu'}

student.update(stud_le) #updatin the dictionary


print('After updating',student)

Output:

(C) Write a program that uses a dictionary that contains ten user names and passwords. The
program should ask the user to enter username and password. If the username is not in the
dictionary, the program should indicate that the person is “not a valid user” of the system. If
the username is in the dictionary, but the user does not enter the right password, the program
should say that “the password is invalid”. If the password is correct, then the program should
display “Welcome”

login={'ram': 1234, 'sam': 5678, 'raj': 4567, 'manu': 9876, 'ford': 7849,
'tata': 4568, 'google': 7412, 'amazon': 41263, 'yahoo': 7854,
'facebook': 1452}
uname=input("enter username ")
password=int(input("enter password "))
if uname in login:
if login.get(uname)==password:
print("Successfully logedin Welcome")
else:
print("this password is invalid ")
else:
print("not a valid user")

Output:

Vardhaman College of Engineering Data Visualization through Python


7. Programs using Python Data Structures (Tuples and Set)
(a) Write a python program to demonstrate various operations on tuples.

t=tuple(map(int,input("Enter integers as a tuple:").split()))


print("Tuple:",t)

print("Length of tuple =",len(t))


print("Repetetion of tuple 5 times =",t*5)

# Print the last item in the tuple.


print("Last character in the tuple :",t[-1])

# Print the tuple in reverse order.


print("Reverse tuple:",t[-1:: -1])

# Print Yes if tuple contains value 5 along with its index, else print No otherwise.
if 5 in t:
print("Yes the element is present at location ",t.index(5))
else:
print("No")

# Print the number of occurrences of a element in the tuple.


element=int(input("Enter an element to check:"))
print(f"number of occurances of {element} in the tuple:",t.count(element))

# Sort the tuple


print("Tuple after sorting:", sorted(t))

# Print how many integers in the tuple are less than a given value?
element=int(input("Enter an element to check:"))
x=0
for i in t:
if(i<element):
x+=1
print(f"Elements less than {element}:",x)

# Print the average of the elements in the tuple.


print(f"Average of tuple:", sum(t)/len(t))

# Print the largest and smallest value in the tuple.


print(f"Smallest:{min(t)}\nLargest:{max(t)}")

# Print number of even numbers in the tuple


x=0
Vardhaman College of Engineering Data Visualization through Python
for i in t:
if(i%2==0):
x+=1
print(f"Elements less than {element}:",x)

Output:

(b) Write a python program to demonstrate various operations on sets.


s = {1,2,3,4,6,9}
t = {4,5,6,1,3,3}
u = {1,2,3,4}

print(f"Set S = {s} T = {t} U = {u}")


print(f"length of sets S = {len(s)} T = {len(t)} U = {len(u)}")
print(f"Minimum of sets S = {min(s)} T = {min(t)} U = {min(u)}")
print(f"Maximum of sets S = {max(s)} T = {max(t)} U = {max(u)}")
print(f"Sum of sets S = {sum(s)} T = {sum(t)} U = {sum(u)}")
print(f"Sets after sorting S = {sorted(s)} T = {sorted(t)} U = {sorted(u)}")

s.add(5)
print('Updated set after add:', s)
s.discard(5)
print('Updated set_after discard:', s)
s.remove(1)
print('Updated set after remove:', s)

print('\nPopped element', s.pop())


print('Updated set after pop:', s)

print(f"Union of set {s} and {t}: ",s.union(t)) #s|t


print(f"Difference of set {s} and {u}: ",s.difference(u)) #s-u
print(f"Intersection of set {s} and {u}: ",s.intersection(u)), #s&u
print(f"Symmetric Difference of set {s} and {u}: ",s.symmetric_difference(u)) #s^u

Vardhaman College of Engineering Data Visualization through Python


s.difference_update(u)
print(f"Difference of set {s} and {u}: ",s)

t.intersection_update(u)
print(f"Intersection of set {t} and {u}: ",t)

u.symmetric_difference_update(s)
print(f"Symmetric Difference of set {u} and {s}: ",u)

print(f"issubset of set {u} and {s}: ",u.issubset(s))


print(f"isdisjoint of set {u} and {s}: ",u.isdisjoint(s))
print(f"issuperset of set {u} and {s}: ",u.issuperset(s))

s.clear()
print('Updated set after clear:', s)

Output:

8. Programs using User Defined Functions.


(a) Write a Python program to calculate simple interest using function

def c_intrest(p,t,r):
#compute compound interest
ci = p * (pow((1 + r / 100), t))
return ci

p = float(input("Enter the principal amount : "))

Vardhaman College of Engineering Data Visualization through Python


t = float(input("Enter the number of years : "))

r = float(input("Enter the rate of interest : "))


Compound_interest=c_intrest(p,t,r)
print("Compound interest : %.2f" %Compound_interest)

Output:

(b) Write a Python program to find the nth term of a Fibonacci number using function
def fib2(n):
a,b=0,1
#print(a,b,end=' ')
for i in range(n):
f=a+b
a=b
b=f
print(f,end=' ')

fib2(int(input("enter value")))

Output:

(c) Write a Python program to find the number of elements in a list using function.

def count_list(ls1):
c=0
for i in ls1:
c=c+1
return c
ls1=[1,2,3,'hello',56.2,'welcome']
print('The number of elements in list are = ',count_list(ls1))

Output:

(d) Write a python program to find factorial of a given number using recursion.

Vardhaman College of Engineering Data Visualization through Python


def ric_factorial(n):
if n==1 or n==0:
return 1
else:
return n*ric_factorial(n-1)
print('The factorial of given number is =', ric_factorial(int(input("enter number "))))

Output:

(e) Write a python program to find sum of individual digits of a given number using recursio

tot = 0
Reminder=5
def sum_of_num(Num):
global tot
if(Num > 0):
Reminder = Num % 10
tot = tot + Reminder
sum_of_num(Num //10)
return tot

Num = int(input("Please Enter any Integer: "))


tot = sum_of_num(Num)
print("Sum of the digits = %d" %(tot))

Output:

9). Programs using Bar charts and Pie charts.


(a) Write a python program to visualize bar and column chart for a given data includes
months on x-axis and prices on y-axis.
(b) Write a python program to visualize plot bar charts and histograms for a given 30
students averages.
(c) The table given shows the sales of books (in thousand number) from six branches of a
publishing company during two consecutive years 2000 and 2001.
i. Write a python to display bar graphs of the sales and use different color for each bar
ii. Write a python to visualize the percentage of sales using pie chars.

Years B1 B2 B3 B4 B5 B6

2020 80 75 98 83 75 72

Vardhaman College of Engineering Data Visualization through Python


2021 105 68 107 95 95 80

(a) Write a python program to visualize bar and column chart for a given data includes months
on x-axis and prices on y-axis.

import pandas as pd
from matplotlib import pyplot as plt

x=['jan', 'feb', 'march', 'april', 'may', 'jun']

y=[10,1.2,4.3,3.4,7.5,2.5]

plt.xlabel('months')
plt.ylabel('price')

plt.title('Half yearly price of an item')

plt.bar(x,y)
plt.show()

Output:

(b) Write a python program to visualize plot bar charts and histograms for a given 30 students
averages.

import pandas as pd
from matplotlib import pyplot as plt

df=pd.read_excel("D:\ADVT_Python\CAT-1\ADVT R21 IT-A CAT-1 MARKS


A7601.xlsx",sheet_name='Comparitions',na_values='')
#df.fillna('0', inplace=True) fill any spaces with o
print(df.head(30))

Vardhaman College of Engineering Data Visualization through Python


dp=df.head(30).copy()
dp['Theory']=dp["Theory"].astype('int64') # Convert Object datatype to int64
dp['Lab']=dp["Lab"].astype('int64')
#dp['Total']=dp["Total"].astype('int64')

avg=(dp['Theory']+dp['Lab'])/2
print(avg.plot(kind='bar'))

Output:

Vardhaman College of Engineering Data Visualization through Python


(c) The table given shows the sales of books (in thousand number) from six branches of a
publishing company during two consecutive years 2000 and 2001.

import pandas as pd
from matplotlib import pyplot as plt

x=['B1', '82', '83', '84', '85', '86']


y=[80,70,60,87,90,79]
z=[105,75,75,120,130,85]

plt.bar(x,y,width=.7, label='sales in 2000')


plt.bar(x,z,width=.4, label='sales in 2001')

plt.legend()
plt.show()

Output:

i. Write a python to display bar graphs of the sales and use different color for each bar

Vardhaman College of Engineering Data Visualization through Python


import pandas as pd
from matplotlib import pyplot as plt

plt.bar(x,y, alpha=.9, label='sales in 2000')


plt.bar(x,z, alpha=.6, label='sales in 2001')

plt.legend()
plt.show()

Output:

ii. Write a python to visualize the percentage of sales using pie chars.

import pandas as pd
from matplotlib import pyplot as plt

plt.figure(0)
plt.pie(y, labels = ['Branch 1','Branch 2','Branch 3','Branch 4','Branch 5','Branch 6'],
autopct='%.0f%%')
plt.title('Sales in 2000')

plt.figure(1)
plt.pie(z, labels = x, autopct='%.0f%%')
plt.title('Sales in 2001')
plt.show()

Output:

Vardhaman College of Engineering Data Visualization through Python


10. Programs using Visualization.
(a) Jerry recorded the temperature in his room (in Degrees Fahrenheit) every two hours
over a 12 hour period from noon to midnight, as Temp=40, 42,45,46,38,36,34. Write a Python
program to visualize the recorded temperatures as line graph.
(b) The population (in thousands) of a town was recorded every twenty years from 1900 to
2000. Population =3, 4,2,5,7,7,7. Write a program to visualize a line graph by taking years on x-
axis.

(a) Jerry recorded the temperature in his room (in Degrees Fahrenheit) every two hours over a
12 hour period from noon to midnight, as Temp=40, 42,45,46,38,36,34. Write a Python
program to visualize the recorded temperatures as line graph.

import pandas as pd
from matplotlib import pyplot as plt

time=[12, 2, 4, 6, 8, 10, 12]


tmp=[40, 42, 45, 46, 38, 36, 34]
plt.xlabel('Time')
plt.ylabel("Temperature")
plt.plot(time,tmp)
plt.show()

Output:
Vardhaman College of Engineering Data Visualization through Python
(b) The population (in thousands) of a town was recorded every twenty years from 1900 to
2000. Population =3, 4,2,5,7,7,7. Write a program to visualize a line graph by taking years on x-
axis.

import pandas as pd
from matplotlib import pyplot as plt

year=[1900, 1920, 1940, 1960, 1980, 2000]


pepl=[3, 4, 2, 5, 7, 7]

plt.xlabel('Year')
plt.ylabel("Population in thousands")
plt.plot(year,pepl)
plt.show()

Output:

12. Programs using Datasets.


(a) You are required to construct two datasets with the GPA of two classes each of 60
students.

Vardhaman College of Engineering Data Visualization through Python


i. Write a Python program to compare the GPA distribution of each using a suitable
Visualization approach and what can you infer from the distributions.
ii. Write a program to display Boxplot analysis for the same.
(b) Write a python program to implement the following on iris data set
i. Visualize the petal length, petal width, sepal length, sepal width.
ii. Visualize average of each.
iii. What can you infer from the visualization? Throw the major insights you have observed
from the visualizations.

(a) You are required to construct two datasets with the GPA of two classes each of 60 students.
i. Write a Python program to compare the GPA distribution of each using a suitable
Visualization approach and what can you infer from the distributions.

import matplotlib.pyplot as plt


import pandas as pd

GPA_set=pd.read_table("D:\ADVT_Python\IRIS & other Data


Sets\Student_GPA.txt",index_col=0)
print(GPA_set)

GPA_set.plot(kind='box')
plt.show()

Vardhaman College of Engineering Data Visualization through Python


Output:

i. Visualize the petal length, petal width, sepal length, sepal width.

import matplotlib.pyplot as plt


import pandas as pd
from sklearn.datasets import load_iris

iris=load_iris()
iris

Output:

Vardhaman College of Engineering Data Visualization through Python


Vardhaman College of Engineering Data Visualization through Python
Vardhaman College of Engineering Data Visualization through Python
12. Programs using Heat Maps.
(a) Write a program to visualize the correlations between various numeric features of iris
data using heat maps.
(b) Write a python program to visualize the correlations between various numeric features
of the Titanic data and analyze which features are more important.

Vardhaman College of Engineering Data Visualization through Python


(b) Write a python program to visualize the correlations between various numeric features of
the Titanic data and analyze which features are more important.

import pandas as pd

titanic_set=pd.read_table("D:\ADVT_Python\IRIS & other Data Sets\Titanic.txt")


print(titanic_set)

Vardhaman College of Engineering Data Visualization through Python


Vardhaman College of Engineering Data Visualization through Python
13. Programs using Seaborn.
(a) Write a python program to create violin plots of iris species using seaborn.

Vardhaman College of Engineering Data Visualization through Python


Vardhaman College of Engineering Data Visualization through Python

You might also like