0% found this document useful (0 votes)
28 views46 pages

Python Lab File

Lab file

Uploaded by

mocetow663
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views46 pages

Python Lab File

Lab file

Uploaded by

mocetow663
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 46

BanarsidasChandiwala Institute of Information

Technology
Affiliated to
Guru Govind Singh Indraprastha University, New Delhi

MASTER OF COMPUTER APPLICATION


Python Programming Lab(MCA-166))

Submitted to: Mr. Alok Mishra Submitted by: Sachin Sharma


Designation: Asst. Professor Roll no.: 05411104423
11104423
Sem: MCA 2nd Sem 25
Batch:2023-25
INDEX

S.N Practical Date Signature Page


o. No.
1 Write a program to print “Hello World”.

2 Write a program to compute distance between


two points taking input from the user.

3 Write a python Program for addition,


Subtraction, multiplication, division.

4 Write a python program for converting


Temperature to and from Celsius and
Fahrenheit.

5 Write a python program to Convert Decimal to


Binary, Octal and Hexadecimal.

6 Write a Python program to swap values of Two


Variables without using third variable.

7 Write a python program to Find ASCII Value of


Character.

8 Write a Python Program for checking whether


the given number is an even number or not.

9 Write a Python Program to check leap year

10 Write a Python Program to Check Prime


Number

11 Write a Python program to check whether the


given no is Armstrong or not.
12 Write a Python Program to Find HCF.

13 Write a Python Program to Find LCM.

14 Write a Python Program to Add Two Matrices.

15 Write a Python program to generate list of


Fibonacci number up to n Fibonacci numbers.

16 Write a Python program which takes a list and


returns a list with the elements
“shifted left by one position” so [1, 2, 3] yields
[2, 3, 1].
Example: [1, 2, 3] → [2, 3, 1] & [11, 12, 13] →
[12, 13, 11]

17 Consider the list lst=[9,8,7,6,5,4,3]. Write the


Python program which performs the following
operation:

A. Insert element 10 at beginning of the list.


B. Insert element 2 at end of the list.
C. Delete the element at index position 5.
D. Print all elements in reverse order

18 Write a Python program which will return the


sum of the numbers in the array, returning 0
for an empty array.
Except the number 13is very unlucky, so it
does not count
and number that come immediately after 13
also do not count.
Example : [1, 2, 3, 4] = 10 , [1, 2, 3, 4, 13] = 10 ,
[13, 1, 2, 3,
13] = 5

19 Write a Python program to Check Whether a


String is Palindrome or Not.

20 Write a Python program to Illustrate Different


Set Operations.

21 Write a python program to do the following :


A. To sum all the items in a list.
B. To multiplies all the items in a list.
C. To get the largest number from a list.
D. To get the smallest number from a list
E. To remove duplicates from a list
F. To check a list is empty or not
G. To select an item randomly from a list.
H. To clone or copy a list
I. To find the second smallest number in a
list.
J. To find the second largest number in a list
K. To get unique values from a list.
L. To remove the K’th element from a given
list, print the new list.
M. To insert an element at a specified position
into a given list

22 Write a Python program to sort a dictionary by


value.

23 Write a Python program to add a key to a


dictionary.
Sample Dictionary: {0: 100, 1: 200}
Expected Result: {0: 100, 1: 200, 2: 300}
Write a Python program to print a dictionary
where the keys are numbers
between 1 and 5 (both included) and the
values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

24 Write a Python program to do the following:


A. To Sort a dictionary by key.
B. To get the maximum and minimum value in
a dictionary.
C. To remove duplicates from Dictionary.

25 Write a function find_longest_word() that


takes a list of words
and returns the length of the longest one.

26 Write a Python program that counts the


number of occurrences of the character in the
given string using function. Provide two
implementations: recursive and iterative.

27 Write a Python program to find reverse of


given number using user defined function.

28 Write a python program to implement is


Palindrome () function to check given string is
palindrome or not.

29 Write a program to compute the number of


characters, words and lines in a file.

30 Write a python program to know the current


working directory and to print all contents of
the current directory. What changes we need
to make in the program if we wish to display
the contents of only ‘mysub’ directory
available in current directory?

31 Write a python program to append data to an


existing file ‘python.py’. Read data to be
appended from the user. Then display
the contents of entire file.

32 Write a python program to retrieve name and


date of birth (mm-dd-yyyy) of students from a
given file student.txt.

33 Write a python program to read line by line


from a given files file1 & file2 and write into
file3.

34 Read a text file in Python and print no. of lines


and no. of unique words.

35 Write a python program to illustrate the oops


concepts.

36 Write a python program to illustrate the


exception handling.

37 Write a python to create one dimensional


array.

38 Write a python program to illustrate pandas


library.

39 Write a python program using Tkinter to create


the GUI Interface.
1. Write a program to print “Hello World”.

Program-
print(“Hello World”)
Output-
2. Write a program to compute distance between two points taking input from the
user.
Program -
def distance():
x1 = float(input("Enter the x coordinate of the first point: "))
x-coordinate
y1 = float(input("Enter the y coordinate of the first point: "))
y-coordinate
x2 = float(input("Enter the x
x-coordinate
coordinate of the second point: "))
y2 = float(input("Enter the y
y-coordinate
coordinate of the second point: "))
distancee = ((x2 - x1)**2 + (y2 - y1)**2)**0.5

print("The distance between the two points is: ", distance)


distance()

Output:-
3. Write a python program for addition, Subtraction, multiplication, division.
Program –
defarithmetic_operations():
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: ")
addition = num1 + num2
print("The sum of {0} and {1} is: {2}".format(num1, num2, addition))

subtraction = num1 - num2


print("The difference between {0} and {1} is: {2}".format(num1, num2,
subtraction))

multiplication = num1 * num2


print("The product of {0} and {1} is: {2}".format(num1, num2,
multiplication))

division = num1 / num2


print("The quotient of {0} and {1} is: {2}".format(num1, num2,
division))

arithmetic_operations()

Output –
4. Write a python program for converting Temperature to and fromCelsius and
Fahrenheit.
Program –

defcelsius_to_fahrenheit():
celsius = float(input("Enter the temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("{0} degrees Celsius is equal to {1} degrees
Fahrenheit".format(celsius, fahrenheit))

deffahrenheit_to_celsius():
fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print("{0} degrees Fahrenheit is equal to {1} degrees
Celsius".format(fahrenheit, celsius))

def main():
print("Temperature Conversion Program")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
choice = int(input("Enter your choice (1/2): "))

if choice == 1:
celsius_to_fahrenheit()
elif choice == 2:
fahrenheit_to_celsius()
else:
print("Invalid choice")

main()
Output –
5. Write a python program to convert Decimal to Binary, Octal and Hexadecimal.
Program-
defdecimal_to_binary():
decimal = int(input("Enter a decimal number: "))
binary = bin(decimal).replace("0b", "")
print("The binary representation of {0} is
{1}".format(decimal, binary))

defdecimal_to_octal():
decimal = int(input("Enter a decimal number: "))
octal = oct(decimal).replace("0o", "")
print("The octal representation of {0} is {1}".format(decimal, octal))

defdecimal_to_hexadecimal():
decimal = int(input("Enter a decimal number: "))
hexadecimal = hex(decimal).replace("0x", "")
print("The hexadecimal representation of {0} is {1}".format(decimal,
hexadecimal))

def main():
print("Number System Conversion Program")
print("1. Convert Decimal to Binary")
print("2. Convert Decimal to Octal")
print("3. Convert Decimal to Hexadecimal")
choice = int(input("Enter your choice (1/2/3): "))

if choice == 1:
decimal_to_binary()
elif choice == 2:
decimal_to_octal()
elif choice == 3:
decimal_to_hexadecimal()
else:
print("Invalid choice")
main()

Output –
6. Write a python program to swap values of two variables without using third
variable.
Program –
def swap():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

num1, num2 = num2, num1


print("The first number after swapping is: ", num1)
print("The second number after swapping is: ", num2)
swap()

Output -
7. Write a python program to find ASCII Value of character.
Program –
defascii_value():
character = input("Enter a character: ")

asciivalue = word(character)
print("The
"The ASCII value of '{0}' is {1}".format(character,
ascii_value))
ascii_value()

Output –
8. Write a python program for checking whether the given number is an even number
or not.
Program –
def even():

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


if num % 2 == 0:
print("{0} is an even number".format(num))
else:
print("{0} is not an even number".format(num))

even()

Output –
9. Write a python program to check leap year.
Program –
defis_leap_year():

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

if year % 4 == 0 and (year % 100!= 0 or year % 400 == 0):


print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
is_leap_year()
Output –
10. Write a python program to check prime number.
Program –
def prime():
num = int(input("Enter a number: "))

if num > 1:
for i in range(2, num):
if num % i == 0:
print("{0} is not a prime number".format(num))
return

print("{0} is a prime number".format(num))


else:
print("{0} is not a prime number".format(num))
prime()

Output –
11. Write a Python program to check whether the given no. is Armstrong or not.
Program –
defarmstrong():
num = int(input("Enter a number: "))

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

if num == sum_of_cubes:
print("{0} is an Armstrong number".format(num))
else:
print("{0} is not an Armstrong number".format(num))

armstrong()

Output –
12. Write a Python Program to find HCF.
Program -
import math
def hcf1():

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))
hcf = math.gcd(num1, num2)
print("The HCF of {0} and {1} is {2}".format(num1, num2, hcf))

hcf1()

Output –
13. Write a Python Program to find LCM.
Program –
def lcm1():

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

lcm = max(num1, num2)


while True:
if lcm % num1 == 0 and lcm % num2 == 0:
break
lcm += 1

print("The LCM of {0} and {1} is {2}".format(num1, num2, lcm))

lcm1()

Output –
14. Write a Python Program to Add Two Matrices.
Program –
def matrices():

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


cols = int(input("Enter the number of columns: "))
matrix1 = [[0 for _ in range(cols)] for _ in range(rows)]
matrix2 = [[0 for _ in range(cols)] for _ in range(rows)]
print("Enter the elements of the first matrix:")
for i in range(rows):
for j in range(cols):
matrix1[i][j] = int(input("Enter element ({0}, {1}):
".format(i+1, j+1)))

print("Enter the elements of the second matrix:")


for i in range(rows):
for j in range(cols):
matrix2[i][j] = int(input("Enter element ({0}, {1}):
".format(i+1, j+1)))
result = [[matrix1[i][j] + matrix2[i][j] for j in range(cols)] for
i in range(rows)]
print("The sum of the matrices is:")
for i in range(rows):
for j in range(cols):
print(result[i][j], end=" ")
print()
matrices()
Output –
15. Write a Python program to generate list of Fibonacci number up to n Fibonacci
numbers.
Program –
deffibonacci(n):
fibonacci_numbers = [0, 1]
while len(fibonacci_numbers) < n:
fibonacci_numbers.append(fibonacci_numbers[ 1] +
fibonacci_numbers.append(fibonacci_numbers[-1]
fibonacci_numbers[-2])
fibonacci_numbers[

return fibonacci_numbers[:n]
n = int(input("Enter the number of Fibonacci numbers: "))

fibonacci_numbers = generate_fibonacci(n)
print("The first {0} Fibonacci numbers are: {1}".format(n,
fibonacci_numbers))

Output –
16. Write a Python program which takestakes a list and returns a list with the elements
“shifted left by one position” so [1,2,3] yields [2,3,1].
Program –
def shift(lst):
if len(lst) <= 1:
return lst
else:
return lst[1:] + [lst[0]]

original_list = [100, 99, 98]


shifted_list = shift(original_list)
print("Original list:", original_list)
print("Shifted list:", shifted_list)

Output –
17. Consider the list lst=[9,8,7,6,5,4,3]. Write the Python program which performs the
following operation.
a. Insert element 10 at beginning of the list.
b. Insert element 2 at end of the list.
c. Delete the element at index position 5.
d. Print all elements in reverse order.
Program –
definsert_at_beginning(lst, element):
lst.insert(0, element)
definsert_at_end(lst, element):
lst.append(element)

defdelete_at_index(lst, index):
del lst[index]

defprint_in_reverse(lst):
for i in range(len(lst)-1, -1, -1):
print(lst[i], end=" ")

lst = [9, 8, 7, 6, 5, 4, 3]

insert_at_beginning(lst, 10)
print("List after inserting 10 at the beginning:", lst)

insert_at_end(lst, 2)
print("List after inserting 2 at the end:", lst)

delete_at_index(lst, 5)
print("List after deleting the element at index position 5:", lst)

print_in_reverse(lst)
print()

Output –
18. Write a Python program which will return the sum of the numbers in the array,
returning 0 for an empty array. Except the number 13 is very unlucky, so it does not
count and number that come immediately after 13 also do not count.
Program –
def sum(nums):
total = 0
i = 0
while i<len(nums):
if nums[i] == 13:
i += 2
else:
total += nums[i]
i += 1
return total

array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 13, 4, 5]
array3 = [13, 1, 2, 3, 4, 5]
array4 = []
print("Sum of array1:",
ay1:", sum(array1))
print("Sum of array2:", sum(array2))
print("Sum of array3:", sum(array3))
print("Sum of array4:", sum(array4))
Output –
19. Write a Python program to Check Whether a String is Palindrome or Not.
Program –
def palindrome(s):

reversed_s = s[::-1]

if s == reversed_s:
return True
else:
return False

s = input("Enter a string: ")

if palindrome(s):
print("{0} is a palindrome".format(s))
else:
print("{0} is not a palindrome".format(s))

Output –
20. Write a Python program to illustrate Different Set Operations.
Program –
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

union = set1 | set2


print("Union of set1 and set2:", union)
intersection = set1 & set2
print("Intersection of set1 and set2:", intersection)
difference = set1 - set2
print("Difference of set1 and set2:", difference)
symmetric_difference = set1 ^ set2
print("Symmetric difference of set1 and set2:", symmetric_difference)

subset = set1 <= set2


print("Is set1 a subset of set2?", subs
subset)

superset = set1 >= set2


print("Is set1 a superset of set2?", superset)

Output –
21. Write a Python program to do the following
a. To sum all the items in a list.
b. To multiplies all the items in a list.
c. To get the largest number from a list.
d. To get the smallest from a list.
e. To remove duplicates from a list.
f. To check a list is empty or not.
g. To select an item randomly from a list.
h. To clone or copy a list.
i. To find the second smallest number in a list.
j. To find the second largest in a list.
k. To get unique values from a list.
l. To remove the K’th element from a given list, print the new list.
m. To insert an element at a specified position into a given list.
Program –
import random

defsum_list(lst):
return sum(lst)

defmultiply_list(lst):
result = 1
for item in lst:
result *= item
return result

defget_largest(lst):
return max(lst)

defget_smallest(lst):
return min(lst)

defremove_duplicates(lst):
return list(set(lst))

defis_empty(lst):
return len(lst) == 0

defselect_random(lst):
return random.choice(lst)

defclone_list(lst):
return lst.copy()
defsecond_smallest(lst):
unique_sorted = sorted(set(lst))
if len(unique_sorted) < 2:
return "List doesn't have enough elements"
return unique_sorted[1]

defsecond_largest(lst):
unique_sorted = sorted(set(lst))
if len(unique_sorted) < 2:
return "List doesn't have enough elements"
return unique_sorted[-2]

defget_unique_values(lst):
return list(set(lst))

defremove_kth_element(lst, k):
if k < 0 or k >= len(lst):
return "Invalid index"
del lst[k]
return lst

definsert_element(lst, element, position):


lst.insert(position, element)
return lst

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]

print("Sum of list:", sum_list(my_list))


print("Product of list:", multiply_list(my_list))
print("Largest number:", get_largest(my_list))
print("Smallest number:", get_smallest(my_list))
print("List without duplicates:", remove_duplicates(my_list))
print("Is the list empty?", is_empty(my_list))
print("Random item from list:", select_random(my_list))
print("Clone of list:", clone_list(my_list))
print("Second smallest number:", second_smallest(my_list))
print("Second largest number:", second_largest(my_list))
print("Unique values in list:", get_unique_values(my_list))
print("List with 2nd element removed:",
remove_kth_element(my_list, 1))
print("List with element inserted at position 2:",
insert_element(my_list, 8, 2))
Output –
22. Write a Python program to sort a dictionary by value.
Program –
def sort(d):
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
return sorted_d

d = {'a': 2, 'b': 1, 'c': 5, 'd': 4, 'e': 3}


sorted_d = sort(d)
print("Sorted dictionary by value:", sorted_d)

Output –
23. Write a Python program to add a key to a dictionary.
Program –
my_dict = {'a': 1, 'b': 2, 'c': 3}
defadd_key(dictionary, key, value):
dictionary[key] = valu
add_key(my_dict, 'd', 4)
print("Updated dictionary:", my_dict)

Output –
24. Write a Python program to do the following :
a. To sort a dictionary by key.
b. To get the maximum and minimum value in a dictionary.
c. To remove duplicates from dictionary.
Program –
def sort(dictionary):
sorted_dict = dict(sorted(dictionary.items()))
return sorted_dict
defmax_min_values(dictionary):
if not dictionary:
return None, None
max_val = max(dictionary.values())
min_val = min(dictionary.values())
return max_val, min_val
defremove_duplicates_from_dict(dictionary):
unique_dict = {}
for key, value in dictionary.items():
if value not in unique_dict.values():
unique_dict[key] = value
return unique_dict
my_dict = {'b': 2, 'a': 1, 'd': 4, 'c': 3, 'e': 2}
sorted_dict = sort(my_dict)
print("Sorted dictionary by key:", sort
sorted_dict)

Output –
25. Write a function find_longest_word() that takes a list of words and returns the
length of the longest one.
Program –
deffind_longest_word(words):
longest_word_length = max(len(word) for word in words)

return longest_word_length

words = ['apple', 'banana', 'cherry', 'date', 'fig']

longest_word_length = find_longest_word(words)

print("The length of the longest word is:", longest_word_length)

Output –
26. Write a Python program that counts the number of occurrences of the character in
the given string using function. Provide two implementations: recursive and
iterative.
Program-
 Recursive
def recursive(string, char):
if len(string) == 0:
return 0
if string[0] == char:
return 1 + recursive(string[1:],
recursive(strin char)
else:
return recursive(string[1:], char)

# Test the function


input_string = "hello world"
character = "l"
print("Number of occurrences (recursive):",
recursive(input_string, character))

Output –
 Iterative
def iterative(string, char):
count = 0
for c in string:
if c == char:
count += 1
return count
input_string = "hello world"
character = "l"
print("Number of occurrences
(iterative):",iterative(input_string, character))

Output –
27. Write a Python program to find reverse of given number using user defined
function.
Program –
defreverse_number(n):
n_str = str(n)

reversed_n_str = n_str[::-1]
n_str[::

reversed_n = int(reversed_n_str)

return reversed_n

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

reversed_n = reverse_number(n)

print("The reverse of the number is:", reversed_n)

Output –
28. Write a Python program to implement is Palindrome() function to check given
string is palindrome or no.
Program –
def palindrome(string):
string = string.lower().replace(" ", "")
return string == string[::
string[::-1]
input_string = "A man a plan a canal Panama"
print("Is the string a palindrome?", palindrome(input_string))

Output –
29. Write a python program to illustrate the oops concepts.
Program –
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

def perimeter(self):
return 2 * (self.width + self.height)

rectangle = Rectangle(5, 10)


print("Area:", rectangle.area())
print("Perimeter:", rectangle.perimeter())

Output –
30. Write a python program to illustrate the exception handling.
Program –
try:
numerator = 10
denominator = 0

result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")

Output –
31. Write a python program to create one dimensional array.
Program –
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Array:", array)

print("Element at index 5:", array[5])


array[5] = 100

print("Modified array:", array)

array.append(10)
print("Array with added element:", array)

array.pop()
print("Array with removed element:", array)

Output –
32. Write a python program to illustrate pandas library.
Program –
import pandas as pd

data = {
'Name': ['Saurabh', 'Sachin', 'Tushar', 'Mohit'],
'Age': [22, 23, 22, 32],
'City': ['New Delhi', 'Firozabad', 'Badarpur', 'New Delhi']
}
df = pd.DataFrame(data)

print("DataFrame:")
print(df)

print("\nName column:")
print(df['Name'])

print("\nRows with index 0 and 2:")


print(df.loc[[0, 2]])

print("\nRows with age greater than 30:")


print(df[df['Age'] > 30])
df['Salary'] = [50000, 60000, 70000, 80000]
print("\nUpdatedDataFrame:")
print(df)

mean_age = df['Age'].mean()
print("\nMean age:", mean_age)
total_salary = df['Salary'].sum()
print("\nTotal
nTotal salary:", total_salary)
Output –

You might also like