Python Lab File
Python Lab File
Technology
Affiliated to
Guru Govind Singh Indraprastha University, New Delhi
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
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))
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: "))
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():
even()
Output –
9. Write a python program to check leap year.
Program –
defis_leap_year():
if num > 1:
for i in range(2, num):
if num % i == 0:
print("{0} is not a prime number".format(num))
return
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():
hcf1()
Output –
13. Write a Python Program to find LCM.
Program –
def lcm1():
lcm1()
Output –
14. Write a Python Program to Add Two Matrices.
Program –
def matrices():
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]]
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
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}
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
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
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
longest_word_length = find_longest_word(words)
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)
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)
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)
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)
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'])
mean_age = df['Age'].mean()
print("\nMean age:", mean_age)
total_salary = df['Salary'].sum()
print("\nTotal
nTotal salary:", total_salary)
Output –