Python Practical
Python Practical
Practical File Of
Problem Solving using
Python Programming
23CS001
Submitted
of
BACHELEOR OF ENGINEERING
in
CHITKARA UNIVERSITY
December, 2023
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
Solution:
# Python Program to find the area of triangle
s = (a + b + c) / 2
Output:
Solution:
x=5
y = 10
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
Solution:
#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
Solution:
Output:
Enter a number: 5
This number is Odd
Enter a number: 10
This number is Even
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
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
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
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
Solution:
# checking condition
if num % 2 != 0:
print(num, end = " ")
Output:
Pattern:
1
1 1
1 2 1
1 3 3 1
Solution:
Output:
Pattern:
11111
2222
333
44
5
Solution:
Output:
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:
Function
Solution:
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:
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:
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
Solution:
def string1(input_string):
# Initialize counters
uppercase = 0
lowercase = 0
digit = 0
whitespace = 0
Output:
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.")
common_words(string1, string2)
Output:
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:
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'))
Output:
Solution:
def remove_empty_tuples(tuple_list):
return result_list
filtered_list = remove_empty_tuples(original_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)]
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]
Solution:
def remove_duplicates(dictionary):
result_dict = {}
unique_values = list(set(values))
result_dict[key] = unique_values
return result_dict
input_dict = {
'c': [5, 6, 7, 7, 8]
result_dict = remove_duplicates(input_dict)
print("Original Dictionary:")
print(input_dict)
print(result_dict)
Output:
Original Dictionary:
{'a': [1, 2, 2, 3, 4], 'b': [2, 3, 4, 4, 5], 'c': [5, 6, 7, 7, 8]}
Solution:
def count_frequencies(input_list):
frequency_dict = {}
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:")
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
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)
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
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:
Solution:
def divide_numbers():
try:
print(f"Result: {result}")
except ZeroDivisionError:
except ValueError:
except Exception as e:
divide_numbers()
Output:
Result: 4.0
Problem Solving using Python Programming (23CS001) Page 32
Problem Solving using Python Programming (23CS001)
Solution:
class ListManipulator:
def __init__(self):
self.my_list = []
self.my_list.append(element)
try:
self.my_list.remove(element)
except ValueError:
def display_elements(self):
if not self.my_list:
else:
print(element)
Output:
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
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")
Output:
Solution:
import tkinter as tk
class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("Drawing Application")
self.canvas.bind("<B1-Motion>", self.paint)
self.canvas.bind("<ButtonRelease-1>", self.reset)
self.start_x = None
self.start_y = None
self.start_x = x
self.start_y = y
if __name__ == "__main__":
root = tk.Tk()
app = DrawingApp(root)
root.mainloop()
Problem Solving using Python Programming (23CS001) Page 38