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

Python Practical

This is have to give you only

Uploaded by

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

Python Practical

This is have to give you only

Uploaded by

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

Problem Solving using Python Programming (23CS001)

Practical File Of
Problem Solving using
Python Programming
23CS001
Submitted

in partial fulfillment for the award of the degree

of

BACHELEOR OF ENGINEERING
in

COMPUTER SCIENCE & ENGINEERING

CHITKARA UNIVERSITY

CHANDIGARH-PATIALA NATIONAL HIGHWAY


RAJPURA (PATIALA) PUNJAB-140401 (INDIA)

December, 2023

Submitted To: Submitted By:

Mrs. Prabhjot Kaur Ashish Gusain


Assistant Professor 2210991630
Chitkara University, Punjab Sem, Batch: 1st, 2023
Problem Solving using Python Programming (23CS001) Page 1
Problem Solving using Python Programming (23CS001)

INDEX
Sr. Practical Name Teacher Sign
No.
1 a) Write a Python Program to Calculate the Area of a Triangle
b) Write a Python Program to Swap Two Variables
c) Write a Python Program to Convert Celsius to Fahrenheit
2 a.) Write a Python Program to Check if a Number is Odd or Even
b.) Write a Python Program to Check if a Number is Positive,
Negative or 0
c.) Write a Python Program to Check Armstrong Number
3 a.) Write a Python program to check if a given number is Fibonacci
number?
b.) Write a Python program to print cube sum of first n natural
numbers.
c.) Write a Python program to print all odd numbers in a range.
4 a.) Write a Python Program to Print Pascal Triangle
Hint: Enter number of rows: 4
1
11
121
1331
b.) WAP to Draw the following Pattern for n number:
11111
2222
333
44
5
5 Write a program with a function that accepts a string from keyboard
and create a new string after converting character of each word
capitalized. For instance, if the sentence is “stop and smell the roses”
the output should be “Stop And Smell The Roses”
6 a.) Write a program that accepts a list from user. Your program
should reverse the content of list and display it. Do not use reverse ()
method.
b) Find and display the largest number of a list without using built-in
function max (). Your program should ask the user to input values in
list from keyboard.
7 Find the sum of each row of matrix of size m x n. For example, for the
following matrix output will be like this:
2 11 7 12
5 2 9 15
8 3 10 42
Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63

Problem Solving using Python Programming (23CS001) Page 2


Problem Solving using Python Programming (23CS001)

8 a) Write a program that reads a string from keyboard and display:


* The number of uppercase letters in the string.
* The number of lowercase letters in the string.
* The number of digits in the string.
* The number of whitespace characters in the string.
b) Python Program to Find Common Characters in Two Strings.
c) Python Program to Count the Number of Vowels in a String.
9 a) Write a Python program to check if a specified element presents in
a tuple of
tuples.
Original list:
((‘Red’ ,’White’ , ‘Blue’),(‘Green’, ’Pink’ , ‘Purple’), (‘Orange’,
‘Yellow’,‘Lime’))
Check if White present in said tuple of tuples! True
Check if Olive present in said tuple of tuples! False
b) Write a Python program to remove an empty tuple(s) from a list of
tuples.
Sample data: [(),(),(“,),(‘a’,’b’),(‘a’,’b’,’c’),(‘d’)]
Expected output: [(“,),(‘a’,’b’),(‘a’,’b’,’c’),’d’]
10 a) Write a Program in Python to Find the Differences Between Two
Lists Using Sets.
11 a) Write a Python program Remove duplicate values across
Dictionary Values.

Input : test_dict = {‘Manjeet’: [1], ‘Akash’: [1, 8, 9]}


Output : {‘Manjeet’: [], ‘Akash’: [8, 9]}
Input : test_dict = {‘Manjeet’: [1, 1, 1], ‘Akash’: [1, 1, 1]}
Output : {‘Manjeet’: [], ‘Akash’: []}
b) Write a Python program to Count the frequencies in a list using
dictionary in
Python.
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,4, 4, 4, 2, 2, 2, 2]
Output :
1:5
2:4
3:3
4:3
5:2
Explanation : Here 1 occurs 5 times, 2 occurs 4 times and so on...

12 a) Write a Python Program to Capitalize First Letter of Each Word in


a File.
b.) Write a Python Program to Print the Contents of File in Reverse
Order.
13 WAP
to catch an exception and handle it using try and except code blocks.

Problem Solving using Python Programming (23CS001) Page 3


Problem Solving using Python Programming (23CS001)

14 Write a Python Program to Append, Delete and Display Elements of a


List using Classes.
15 Write a Python Program to Find the Area and Perimeter of the Circle
using Class.
16 Create an interactive application using Python Tkinter library for
graphics programming.

Problem Solving using Python Programming (23CS001) Page 4


Problem Solving using Python Programming (23CS001)

Program 1(A): Title of program: Area of Triangle

Solution:
# Python Program to find the area of triangle

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


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

s = (a + b + c) / 2

# Area of triangle formula


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is:”, area)

Output:

Enter first side:3


Enter second side:4
Enter third side:5
The area of the triangle is 6.00

Problem Solving using Python Programming (23CS001) Page 5


Problem Solving using Python Programming (23CS001)

Program 1(B): Title of program: Swapping Two Variables

Solution:

#Python program to swap two variables

x=5
y = 10

x = input('Enter value of x: ')


y = input('Enter value of y: ')

#Taking a temporary variable


temp = x
x=y
y = temp

print('The value of x after swapping:',x)


print('The value of y after swapping:',y)

Output:
Enter value of x: 3
Enter value of y: 4
The value of x after swapping: 4
The value of y after swapping: 3

Problem Solving using Python Programming (23CS001) Page 6


Problem Solving using Python Programming (23CS001)

Program 1(C): Title of program: Celsius to Fahrenheit

Solution:

#Python Program to convert temperature in celsius to fahrenheit

celsius = float(input("Enter the celsius value: "))

#Calculate fahrenheit
fahrenheit = (celsius * (9/5)) + 32
print("The fahrenheit value is:",fahrenheit)

Output:
Enter the celsius value: 0
The fahrenheit value is: 32.0

Problem Solving using Python Programming (23CS001) Page 7


Problem Solving using Python Programming (23CS001)

Program 2(A): Title of program: Odd or Even Number

Solution:

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


if (num % 2) == 0:
print("This number is Even")
else:
print("This number is Odd")

Output:
Enter a number: 5
This number is Odd

Enter a number: 10
This number is Even

Problem Solving using Python Programming (23CS001) Page 8


Problem Solving using Python Programming (23CS001)

Program 2(B): Title of program: Positive or Negative Number

Solution:
num = float(input("Enter a number: "))

If num > 0:
print("It is a Positive number")

elif num == 0:
print("It is a Zero")

else:
print("It is a Negative number")

Output:
Enter a number: 5
It is a Positive number

Enter a number: -5
It is a Negative number

Enter a number: 0
It is a Zero

Problem Solving using Python Programming (23CS001) Page 9


Problem Solving using Python Programming (23CS001)

Program 2(C): Title of program: Armstrong Number

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

sum = 0

temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output:
Enter a number: 153
153 is an Armstrong number

Enter a number: 127


127 is not an Armstrong number

Problem Solving using Python Programming (23CS001) Page 10


Problem Solving using Python Programming (23CS001)

Program 3(A): Title of program: Fibonacci Number

Solution:
#Python program to check a number is Fibonacci number or not.

n=int(input())
a=1
b=1
c=1
if n==0 or n==1:
print(n, "is a Fibonacci number")
while c<n:
c=a+b
a=b
b=c
if c==n:
print(n, "is a Fibonacci number")
else:
print(n, "is not a Fibonacci number")

Output:

Enter a number:35
35 is not a fibbonaci number

Enter a number:55
55 is a fibbonaci number

Problem Solving using Python Programming (23CS001) Page 11


Problem Solving using Python Programming (23CS001)

Program 3(B): Title of program: Cube of First n Natural Numbers

Solution:
#Python Program to find the cubes of first n natural numbers.

n=int(input("Enter a number"))
sum=0
for i in range(1,n+1):
digit=i**3
sum=digit+sum
print(sum)

Output:

Enter a number:10
1
9
36
100
225
441
784
1296
2025
3025

Problem Solving using Python Programming (23CS001) Page 12


Problem Solving using Python Programming (23CS001)

Program 3(C): Title of program: Odd numbers in a range

Solution:

#Python program to print odd Numbers in given range

start=int(input("Enter a a number to start from:"))


end=int(input("Enter the last number of range:"))

#Using for loop


for num in range(start, end + 1):

# checking condition
if num % 2 != 0:
print(num, end = " ")

Output:

Enter a a number to start from:5


Enter the last number of range:20
5 7 9 11 13 15 17 19

Program 4(A): Title of program: Pascal Triangle


Problem Solving using Python Programming (23CS001) Page 13
Problem Solving using Python Programming (23CS001)

Pattern:

1
1 1
1 2 1
1 3 3 1

Solution:

n=int(input("Enter number of rows:"))


for i in range(n+1):
for j in range(n-i):
print('',end="")
c=1
for j in range(1,i+1):
print(c,'',sep='',end='')
c=c*(i-j)//j
print()

Output:

Enter number of rows:4


1
11
121
1331

Program 4(B): Title of program: Capitalizing words of a String


Problem Solving using Python Programming (23CS001) Page 14
Problem Solving using Python Programming (23CS001)

Pattern:

11111
2222
333
44
5

Solution:

n=int(input("Enter number of rows:"))


for i in range(n):
for j in range(n-i):
print(i+1,end="")
print()

Output:

Enter number of rows:5


11111
2222
333
44
5

Program 5: Title of program: Capitalizing words of a String


Problem Solving using Python Programming (23CS001) Page 15
Problem Solving using Python Programming (23CS001)

Solution:
#Python program with a function that accepts a string from keyboard and create a new
string after converting character of each word capitalized.

sentence=input("Enter a sentence")
def capitalize(sentence):
words=sentence.split()
capitalWords=[word.capitalize() for word in words]
return " ".join(capitalWords)
result=capitalize(sentence)
print("Capitalized Sentence:",result)

Output:

Enter a sentence: stop and smell the roses


Capitalized Sentence: Stop And Smell The Roses

Program 6(A): Title of program: Reverse of a List without reverse()


Problem Solving using Python Programming (23CS001) Page 16
Problem Solving using Python Programming (23CS001)

Function

Solution:

# Python program to reverse a list using reverse() function

def rev(li):
print("The reverse of list is",li[::-1])
n=int(input("No. of items to be in a list:"))
li=[]
for i in range(n):
value=int(input("Enter a item to be in a list"))
li.append(value)
rev(li)

Output:

No. of items to be in a list:5


Enter a item to be in a list:24
Enter a item to be in a list:37
Enter a item to be in a list:43
Enter a item to be in a list:51
Enter a item to be in a list:35
The list is: [24, 37, 43, 51, 35]
The reverse of list is [35, 51, 43, 37, 24]

Program 6(B): Title of program: Largest number in a List without


max() function.
Problem Solving using Python Programming (23CS001) Page 17
Problem Solving using Python Programming (23CS001)

Solution:

#Python program to print the largest number from a list without using max()
function
def largest(li):
print("the largest number is",li[i])
n=int(input("enter number of items in list"))
li=[]
for i in range(n):
value=int(input("Enter a item to be in list"))
li.append(value)
li.sort()
largest(li)

Output:

No. of items to be in a list:5


Enter a item to be in a list:24
Enter a item to be in a list:37
Enter a item to be in a list:43
Enter a item to be in a list:51
Enter a item to be in a list:35
The list is: [24, 37, 43, 51, 35]
The largest of list is:51

Program 7: Title of program: Find the sum of each row of matrix of


size
Problem Solving using Python Programming (23CS001) Page 18
Problem Solving using Python Programming (23CS001)

m x n.

Solution:

# Example matrix
matrix = [
[10, 5, 17],
[3, 8, 20],
[12, 18, 33]
]

def sum_of_rows(matrix):
for i, row in enumerate(matrix, start=1):
row_sum = sum(row)
print(f"Sum of row {i} = {row_sum}")

sum_of_rows(matrix)

Output:

Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63

Problem Solving using Python Programming (23CS001) Page 19


Problem Solving using Python Programming (23CS001)

Program 8(A): Title of program: Reads a string from keyboard and


Display.

Solution:

def string1(input_string):
# Initialize counters
uppercase = 0
lowercase = 0
digit = 0
whitespace = 0

for char in input_string:


if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
whitespace_count += 1

print("Number of uppercase letters:", uppercase)


print("Number of lowercase letters:", lowercase)
print("Number of digits:", digit)
print("Number of whitespace characters:", whitespace)

user_input = input("Enter a string: ")


string1(user_input)

Output:

Enter a string: Hello There! 123


Number of uppercase letters: 2
Number of lowercase letters: 8
Number of digits: 3
Number of whitespace characters: 2

Problem Solving using Python Programming (23CS001) Page 20


Problem Solving using Python Programming (23CS001)

Program 8(B): Title of program: Common characters in two strings.


Solution:

def common_words(str1, str2):


words1 = str1.split()
words2 = str2.split()

set1 = set(words1)
set2 = set(words2)

common_words_set = set1.intersection(set2)

if common_words_set:
print("Common words:", ', '.join(common_words_set))
else:
print("No common words found.")

string1 = input("Enter the first string: ")


string2 = input("Enter the second string: ")

common_words(string1, string2)

Output:

Enter the first string: Hello! Welcome to python.


Enter the second string: Hello! Welcome here at library.
Common words: Hello!, Welcome

Problem Solving using Python Programming (23CS001) Page 21


Problem Solving using Python Programming (23CS001)

Program 8(C): Title of program: Count number of vowels in string.

Solution:
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O'
or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

Output:

Enter string: Hello


Number of vowels are:

Problem Solving using Python Programming (23CS001) Page 22


Problem Solving using Python Programming (23CS001)

Program 9(A): Title of program: Check elements are present in tuples.

Solution:
def check_element_in_tuple(element, tuple_of_tuples):
flat_tuple = tuple(item for sublist in tuple_of_tuples for item in sublist)

if element in flat_tuple:
return True
else:
return False
original_tuple = (('Red', 'White', 'Blue'), ('Green', 'Pink', 'Purple'), ('Orange',
'Yellow', 'Lime'))

result_white = check_element_in_tuple('White', original_tuple)


print(f"Check if White present in the tuple of tuples: {result_white}")
result_olive = check_element_in_tuple('Olive', original_tuple)
print(f"Check if Olive present in the tuple of tuples: {result_olive}")

Output:

Check if White present in the tuple of tuples: True


Check if Olive present in the tuple of tuples: False

Problem Solving using Python Programming (23CS001) Page 23


Problem Solving using Python Programming (23CS001)

Program 9(B): Title of program: Remove empty tuples from list of


tuples.

Solution:
def remove_empty_tuples(tuple_list):

result_list = [tup for tup in tuple_list if tup]

return result_list

original_list = [(1, 2), (), (3, 4), (), (5, 6), ()

filtered_list = remove_empty_tuples(original_list)

print("Original List of Tuples:", original_list)

print("List of Tuples after removing empty tuples:", filtered_list)

Output:

Original List of Tuples: [(1, 2), (), (3, 4), (), (5, 6), ()]
List of Tuples after removing empty tuples: [(1, 2), (3, 4), (5, 6)]

Problem Solving using Python Programming (23CS001) Page 24


Problem Solving using Python Programming (23CS001)

Program 10: Title of program: Difference between two lists using sets.

Solution:
def common_words(str1, str2):
words1 = str1.split()
words2 = str2.split()
set1 = set(words1)
set2 = set(words2)
common_words_set = set1.intersection(set2)
if common_words_set:
print("Common words:", ', '.join(common_words_set))
else:
print("No common words found.")
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
common_words(string1, string2)

Output:

Differences:
In the first list but not in the second: [1, 2]
In the second list but not in the first: [6, 7]

Problem Solving using Python Programming (23CS001) Page 25


Problem Solving using Python Programming (23CS001)

Program 11(A): Title of program: Remove duplicate values across


Dictionary values.

Solution:
def remove_duplicates(dictionary):

result_dict = {}

for key, values in dictionary.items():

unique_values = list(set(values))

result_dict[key] = unique_values

return result_dict

input_dict = {

'a': [1, 2, 2, 3, 4],

'b': [2, 3, 4, 4, 5],

'c': [5, 6, 7, 7, 8]

result_dict = remove_duplicates(input_dict)

print("Original Dictionary:")

print(input_dict)

print("\nDictionary with Duplicate Values Removed:")

print(result_dict)

Problem Solving using Python Programming (23CS001) Page 26


Problem Solving using Python Programming (23CS001)

Output:

Original Dictionary:
{'a': [1, 2, 2, 3, 4], 'b': [2, 3, 4, 4, 5], 'c': [5, 6, 7, 7, 8]}

Dictionary with Duplicate Values Removed:


{'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [8, 5, 6, 7]}

Problem Solving using Python Programming (23CS001) Page 27


Problem Solving using Python Programming (23CS001)

Program 11(A): Title of program: Remove duplicate values across


Dictionary values.

Solution:
def count_frequencies(input_list):

frequency_dict = {}

for element in input_list:

if element in frequency_dict:

frequency_dict[element] += 1

else:

frequency_dict[element] = 1

return frequency_dict

input_list = [1, 2, 2, 3, 4, 1, 5, 2, 3, 1, 4, 4, 5]

result_dict = count_frequencies(input_list)

print("Element Frequencies:")

for key, value in result_dict.items():

print(f"{key}: {value} times")

Output:

Element Frequencies:
1: 3 times
2: 3 times
3: 2 times
Problem Solving using Python Programming (23CS001) Page 28
Problem Solving using Python Programming (23CS001)

4: 3 times
5: 2 times

Problem Solving using Python Programming (23CS001) Page 29


Problem Solving using Python Programming (23CS001)

Program 12(A): Title of program: Capitalize First Letter of Each Word


in a file.

Solution:
def capitalize_first_letter_in_file(input_file, output_file):
try:
with open(input_file, 'r') as file:
content = file.read()
modified_content = ' '.join(word.capitalize() for word in content.split())
with open(output_file, 'w') as file:
file.write(modified_content)

print(f"Successfully capitalized the first letter of each word in {input_file} and


saved to {output_file}")

except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

Output:

it contains some words that need capitalization.

It Contains Some Words That Need Capitalization.

Problem Solving using Python Programming (23CS001) Page 30


Problem Solving using Python Programming (23CS001)

Program 12(B): Title of program: Contents of File in Reverse Order.

Solution:
def print_file_contents_reverse(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
reversed_content = content[::-1]
print(reversed_content)

except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

Output:

This is a sample text file.


It contains some text that we want to reverse.

. .esrever ot tnaw ew taht txet emos stnatsnoc tI


.elif txet elpmas a si sihT

Problem Solving using Python Programming (23CS001) Page 31


Problem Solving using Python Programming (23CS001)

Program 13: Title of program: Catch an exception and handle it using


try and except code block.

Solution:
def divide_numbers():

try:

numerator = int(input("Enter the numerator: "))

denominator = int(input("Enter the denominator: "))

result = numerator / denominator

print(f"Result: {result}")

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Please enter valid integers.")

except Exception as e:

print(f"An unexpected error occurred: {e}")

divide_numbers()

Output:

Enter the numerator: 8

Enter the denominator: 2

Result: 4.0
Problem Solving using Python Programming (23CS001) Page 32
Problem Solving using Python Programming (23CS001)

Error: Cannot divide by zero.

Program 14: Title of program: Append, Delete and Display Elements of


Problem Solving using Python Programming (23CS001) Page 33
Problem Solving using Python Programming (23CS001)

list using classes.

Solution:
class ListManipulator:

def __init__(self):

self.my_list = []

def append_element(self, element):

self.my_list.append(element)

print(f"Element '{element}' appended to the list.")

def delete_element(self, element):

try:

self.my_list.remove(element)

print(f"Element '{element}' deleted from the list.")

except ValueError:

print(f"Error: Element '{element}' not found in the list.")

def display_elements(self):

if not self.my_list:

print("The list is empty.")

else:

print("Elements of the list:")

for element in self.my_list:

print(element)

Problem Solving using Python Programming (23CS001) Page 34


Problem Solving using Python Programming (23CS001)

Output:

Element '1' appended to the list.


Element '2' appended to the list.
Element '3' appended to the list.
Elements of the list:
1
2
3
Element '2' deleted from the list.
Elements of the list:
1
3

Problem Solving using Python Programming (23CS001) Page 35


Problem Solving using Python Programming (23CS001)

Program 15: Title of program: Area and Perimeter of the Circle using
Class.

Solution:
import math

class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
area = math.pi * (self.radius ** 2)
return area
def calculate_perimeter(self):
perimeter = 2 * math.pi * self.radius
return perimeter

radius = float(input("Enter the radius of the circle: "))


circle_instance = Circle(radius)

area = circle_instance.calculate_area()
print(f"Area of the circle: {area:.2f} square units")

perimeter = circle_instance.calculate_perimeter()
print(f"Perimeter of the circle: {perimeter:.2f} units")

Problem Solving using Python Programming (23CS001) Page 36


Problem Solving using Python Programming (23CS001)

Output:

Enter the radius of the circle: 5

Area of the circle: 78.54 square units


Perimeter of the circle: 31.42 units

Problem Solving using Python Programming (23CS001) Page 37


Problem Solving using Python Programming (23CS001)

Program 16: Title of program: Interactive application using Python’s


Tkinter library

Solution:
import tkinter as tk

class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("Drawing Application")

self.canvas = tk.Canvas(root, width=500, height=500, bg="white")


self.canvas.pack(expand=tk.YES, fill=tk.BOTH)

self.canvas.bind("<B1-Motion>", self.paint)
self.canvas.bind("<ButtonRelease-1>", self.reset)

self.start_x = None
self.start_y = None

def paint(self, event):


x, y = event.x, event.y

if self.start_x and self.start_y:


self.canvas.create_line(self.start_x, self.start_y, x, y, width=2, fill="black",
capstyle=tk.ROUND, smooth=tk.TRUE)

self.start_x = x
self.start_y = y

def reset(self, event):


self.start_x = None
self.start_y = None

if __name__ == "__main__":
root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
Problem Solving using Python Programming (23CS001) Page 38

You might also like