0% found this document useful (0 votes)
4 views13 pages

Python Practical2

The document outlines a series of practical exercises for a Python programming lab (CSP-005), covering topics such as operations, control flow, file handling, functions, and Python packages. Each section provides sample code and expected outputs for various programming tasks, including distance calculation, prime number summation, sorting algorithms, and data analysis using libraries like NumPy and Pandas. The exercises aim to enhance programming skills through hands-on practice with Python.

Uploaded by

aamirgour446
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Python Practical2

The document outlines a series of practical exercises for a Python programming lab (CSP-005), covering topics such as operations, control flow, file handling, functions, and Python packages. Each section provides sample code and expected outputs for various programming tasks, including distance calculation, prime number summation, sorting algorithms, and data analysis using libraries like NumPy and Pandas. The exercises aim to enhance programming skills through hands-on practice with Python.

Uploaded by

aamirgour446
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 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(nums):
out = []
prod = 1
for x in nums:
prod = prod * x
[Link](prod)
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

You might also like