PYTHON PROGRAMMING LAB(CSP-005)
GRD INSTITUTE OF MANAGEMENT AND TECHNOLOGY
DEHRADUN
[Link]. Semester- III
PYTHON PROGRAMMING LAB
Subject code: CSP-005
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
Veer Madho Singh Bhandari Uttarakhand Technical University,
Dehradun
Prepared by:- Submitted To:
Katyani Singh Mr. Abhishek Chaudhary
Roll no.750490197004
PYTHON PROGRAMMING LAB (CSP-005)
List of Programs
[Link]. Title of the Programs Date of Date of Signatur
submissi evaluati e
on on
1. a) Running instructions in
Basics interactive
interpreter and a Python
script.
b) Write a program to
purposefully raise an
indentation error and correct it.
2. a) Write a program to compute
Operation distance
s between two points taking
input from the
user (Pythagoras theorem).
b) Write a program to add two
numbers as
command-line arguments and
print their
sum.
3. a) Write a program for checking
Contr whether
ol the given number is an even
Flow number or not.
b) Using a for loop, write a
program that
prints out the decimal
equivalents of 1/2, 1/3, 1/4, …,
1/10.
c) Write a program using a for
loop that
loops over a sequence.
d) Write a program using a
while loop that
asks the user for a number and
prints a
countdown from that number to
zero.
4. a) Find the sum of all the primes
Control below two
Flow million.
Continu b) Write a program to generate
ed the first 10
terms of the Fibonacci sequence
starting
with 1 and 2.
c) By considering terms in the
Fibonacci
sequence whose values do not
exceed four
million, find the sum of the
even-valued
terms.
d) Linear Search
e) Binary Search
f) Selection Sort
g) Insertion Sort
5. a) Write a program to count the
Dictiona number of
ry characters in a string and store
/String them in a
dictionary.
2
PYTHON PROGRAMMING LAB (CSP-005)
b) Write a program to use split
and join
methods in a string and create
a birthday
dictionary.
6. a) Write a program to
Files combine lists that
combine these lists into a
dictionary.
b) Write a program to count
frequency of
characters in a given file.
Can you use character
frequency to
tell whether the file is a
Python
program file, C program file
or a text
file?
7. a) Write a program to print each
Files line of a
file in reverse order.
b) Write a program to compute
the number
of characters, words and lines in
a file.
8. a) Write a function ball_collide
Function that takes
s
two balls as parameters and
computes if they are colliding
b) Find mean, median and mode
for a given
list of numbers.
9. a) Write a function
Function nearly_equal to test
s
whether two strings are
(continu
nearly equal.
ed )
b) Write a function to remove all
duplicates
in a list.
c) Write a function to find all
unique
elements of a list.
10. a) Write a function
Function cumulative_product to
(Proble compute cumulative product of
m- a list.
solving) b) Write a function to reverse a
list without
using the reverse() function.
c) Write a function to compute
the GCD of
two numbers without using
built-in
functions.
11. a) Install packages requests,
Python flask and
explore them using pip.
Packag b) Plot graph using Matplotlib
e c) Data analysis using NumPy
and Pandas
libraries.
3
PYTHON PROGRAMMING LAB (CSP-005)
Practical 1 – Basics
a) Running instructions in interactive interpreter and a Python
script.
name = input("Enter your name: ")
print("Hello", name)
Output:
b) Write a program to purposefully raise an indentation error and
correct it.
Error:
if True:
print("Error")
Output:
Correct:
if True:
print("Correct")
Output:
4
PYTHON PROGRAMMING LAB (CSP-005)
Practical 2 – Operations
a) Write a program to compute distance between two
points taking input from
the user (Pythagoras theorem).
print("Enter values
- \n")
x1 =
float(input("x1: "))
y1 =
float(input("y1: "))
x2 =
float(input("x2: "))
y2 =
float(input("y2: "))
dx = x2 - x1
dy = y2 - y1
distance = (dx*dx + dy*dy)
** 0.5
print("Distance =", distance)
Output:
b) Write a program to add two numbers as command-line arguments
and print
their sum.
a = int(input("Enter first
number: "))
b = int(input("Enter second
number: "))
print("Sum =", a + b)
Output:
5
PYTHON PROGRAMMING LAB (CSP-005)
Practical 3 – Control Flow
a) Write a program for checking whether the given number is an
even number or
not.
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
b) Using a for loop, write a program that prints out the
decimal equivalents of 1/2,
1/3, 1/4, … , 1/10.
for i in range(2, 11):
print("1/", i, "=",
1.0/i)
Output
6
PYTHON PROGRAMMING LAB (CSP-005)
c) Write a program using a for loop that loops over a sequence.
seq = [10, 20, 30, 40]
for x in seq:
print(x)
Output
d) Write a program using a while loop that asks the user for a
number and prints a
countdown from that number to zero.
num = int(input("Enter number: "))
while num >= 0:
print(num)
num = num–1
Output:
7
PYTHON PROGRAMMING LAB (CSP-005)
Practical 4 – Control Flow Continued
a) Find the sum of all the primes below two million.
limit = 2000000
total = 0
for num in range(2, limit):
is_prime = True
# check prime
for i in range(2,
int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
total += num
print("\n Sum of prime numbers upto 2 Million =", total)
Output:
b) Write a program to generate the first 10 terms of the Fibonacci
sequence starting
with 1 and 2.
t1 = 1
t2 = 1
print(t1)
print(t2)
for i in
range(8):
temp = t1 +
t2
print(temp,"
")
t1 = t2
t2 = temp
8
PYTHON PROGRAMMING LAB (CSP-005)
Output:
c) By considering terms in the Fibonacci sequence whose
values do not exceed four
million, find the sum of the even-valued terms.
a, b = 1, 2
total = 0
while b <= 4000000:
if b % 2 ==
0:
total += b
a, b = b, a + b
print(total)
Output
d) Linear Search
arr = [5, 10, 15, 20]
key = int(input("Enter number to
search: "))
found = False
for x in arr:
if x == key:
found = True
break
if found:
print("Found")
else:
print("Not Found")
9
PYTHON PROGRAMMING LAB (CSP-005)
Output
Case 1: Input
= 15
Case 2: Input = 7
e) Binary Search
arr = [2, 4, 6, 8, 10]
key = int(input("Enter search
key: "))
low = 0
high = len(arr) - 1
found = False
while low <= high:
mid = (low + high)
// 2
if arr[mid] == key:
found = True
break
elif arr[mid] < key:
low = mid + 1
else:
high = mid - 1
if found:
print("Found")
else:
print("Not Found")
Output
Case 1: Input
=8
Case 2: Input = 5
10
PYTHON PROGRAMMING LAB (CSP-005)
f) Selection Sort
arr = [64, 25, 12, 22, 11]
for i in range(len(arr)):
min_index = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] =
arr[min_index], arr[i]
print(arr)
Output:
Original list :-
[64, 25, 12, 22,
11]
After Selection Sort:
g) Insertion Sort
arr = [12, 11, 13, 5,
6]
for i in range(1,
len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key <
arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(arr)
OUTPUT
Original list:
[12, 11, 13, 5,
6]
After Insertion Sort:
11
PYTHON PROGRAMMING LAB (CSP-005)
Practical 5 – Dictionary / Strings
a) Write a program to count the number of characters in a
string and store them in
a dictionary.
s = input("Enter
string: ")
count = {}
for ch in s:
if ch in count:
count[ch] = count[ch] + 1
else:
count[ch] = 1
print(count)
Output:
b) Write a program to use split and join methods in a string
and create a birthday
dictionary.
data = "kriti=11-05-2006;
avik=01-01-2000"
items = [Link](";")
bd = {}
for item in items:
parts =
[Link]("=")
name = parts[0]
date = parts[1]
bd[name] = date
print(bd)
Output:
12
PYTHON PROGRAMMING LAB (CSP-005)
Practical 6 – Files
a) Write a program to combine lists that combine these lists into a
dictionary.
f=
open("[Link]",
"r")
lines = [Link]()
[Link]()
for line in lines[::-1]:
print([Link]())
Output:
b) Write a program to count frequency of characters in a given file:
Can you use character frequency to tell whether the file
is a Python program
file, C program file or a text file?
chars = 0
words = 0
lines = 0
f = open("[Link]", "r")
for line in f:
lines = lines + 1
chars = chars + len(line)
words = words +
len([Link]())
[Link]()
print("Lines =", lines)
print("Words =", words)
print("Chars =", chars)
Output:
13
PYTHON PROGRAMMING LAB (CSP-005)
Practical 7 – Files
a) Write a program to print each line of a file in reverse order.
f=
open("[Link]",
"r")
lines = [Link]()
[Link]()
for line in lines[::-
1]:
print([Link]())
Assume [Link] contains:
Hello
How are
you
Python is
easy
Output:
b) Write a program to compute the number of characters, words and
lines in a file.
chars =
0
words
=0
lines =
0
f = open("[Link]", "r")
for line in f:
lines = lines
+1
chars = chars + len(line)
words = words +
len([Link]())
[Link]()
print("Lines =", lines)
print("Words =", words)
print("Chars =", chars)
Output
14
PYTHON PROGRAMMING LAB (CSP-005)
Practical 8 – Functions
a) Write a function ball_collide that takes two balls as
parameters and computes if
they are colliding
def ball_collide(x1, y1, r1, x2,
y2, r2):
d = ((x2-x1)**2 + (y2-y1)**2)
** 0.5
if d <= r1 + r2:
return True
else:
return False
print(ball_collide(0,0,5, 5,0,5))
Output:
b) Find mean, median and mode for a given list of numbers.
nums = [1, 2, 2, 3]
# Mean
mean = sum(nums) / len(nums)
# Median
nums2 =
sorted(nums)
n = len(nums2)
if n % 2 == 1:
median = nums2[n//2]
else:
median = (nums2[n//2] + nums2[n//2 - 1]) / 2
# Mode
mode = None
max_count = 0
for x in nums:
c=
[Link](x)
if c >
max_count:
max_count = c
mode = x
print("Mean =",
mean)
print("Median =",
median)
print("Mode =",
mode)
Output:
15
PYTHON PROGRAMMING LAB (CSP-005)
Practical 9 – Functions
a) Write a function nearly_equal to test whether two strings are
nearly equal.
def nearly_equal(a, b):
if [Link]().lower() == [Link]().lower():
return True
else:
return False
print(nearly_equal("Hello", " hello "))
Output:
b) Write a function to remove all duplicates in a list.
Program:
lst = [1, 2, 2, 3, 1]
unique = []
for x in lst:
if x not in unique:
[Link](x)
print(unique)
Output:
c) Write a function to find all unique elements of a list.
lst = [1, 2, 2, 3, 4, 4, 5]
unique = []
for x in lst:
if [Link](x) == 1:
[Link](x)
print(unique)
Output:
16
PYTHON PROGRAMMING LAB (CSP-005)
Practical 10 – Functions (Problem Solving)
a) Write a function cumulative_product to compute cumulative
product of a list.
def
cumulative_product(nu
ms):
out = []
prod = 1
for x in nums:
prod = prod *
x
[Link](p
rod)
return out
print(cumulative_product([1,2,3,4]))
Output:
b) Write a function to reverse a list without using the reverse()
function.
def
reverse_list(lst):
return lst[::-1]
print(reverse_list([1,2,3,4]))
Output:
c) Write a function to compute the GCD of two numbers without
using built-in
functions.
def gcd(a, b):
while b != 0:
temp = b
b=a%b
a = temp
return a
print(gcd(12, 18))
Output:
17
PYTHON PROGRAMMING LAB (CSP-005)
Practical 11 – Python Packages
a) Install packages requests, flask and explore them using pip.
Command:
pip install
requests
pip install flask
Output (example):
b) Plot graph using Matplotlib
import [Link]
as plt
x = [1,2,3,4]
y = [2,4,6,8]
[Link](x, y)
[Link]("X")
[Link]("Y")
[Link]("Simple Line
Graph")
[Link]()
Output:
c) Data analysis using NumPy and Pandas libraries.
Program:
import numpy
as np
import pandas
as pd
arr = [Link]([1,2,3,4])
print(arr)
df = [Link]({"A":[1,2],
"B":[3,4]})
print(df)
Output:
18