PYTHON PRACTICALS AT
PYTHON PRACTICALS AT
def sum_and_reverse(num):
# Calculate sum of digits
digit_sum = sum(int(digit) for digit in str(num))
# Example usage
num = 12345
sum_result, reverse_result = sum_and_reverse(num)
print("Sum of digits:", sum_result)
print("Reverse of the number:", reverse_result)
# Example usage
num = 12321
print("Is palindrome?", is_palindrome(num))
# Example usage
n = 10
print("Fibonacci series:", fibonacci(n))
# Append method
my_list.append(6)
print("List after append:", my_list)
# Pop method
my_list.pop()
print("List after pop:", my_list)
# Index method
index = my_list.index(3)
print("Index of 3:", index)
# Reverse method
my_list.reverse()
print("Reversed list:", my_list)
6. WAP to find the repeated elements of a list.
def find_duplicates(lst):
duplicates = []
for item in lst:
if lst.count(item) > 1 and item not in duplicates:
duplicates.append(item)
return duplicates
# Example usage
my_list = [1, 2, 2, 3, 4, 4, 5]
print("Repeated elements:", find_duplicates(my_list))
7. WAP using list comprehension to create a list of cubes of all nos up to 10.
cubes = [x**3 for x in range(1, 11)]
print("Cubes of numbers up to 10:", cubes)
8. WAP using list comprehension to create a list of squares of all even nos from a given list.
given_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares_of_evens = [x**2 for x in given_list if x % 2 == 0]
print("Squares of even numbers:", squares_of_evens)
9. WAP using list comprehension to include all strings in given list except those with letter ‘a’.
given_list = ["apple", "banana", "orange", "grape", "kiwi"]
filtered_list = [s for s in given_list if 'a' not in s]
print("Filtered list:", filtered_list)
10. WAP to create a tuple and demonstrate any four tuple methods/functions
my_tuple = (1, 2, 3, 4, 5)
# Index method
index = my_tuple.index(3)
print("Index of 3:", index)
# Count method
count = my_tuple.count(2)
print("Count of 2:", count)
# Tuple concatenation
new_tuple = my_tuple + (6, 7, 8)
print("Concatenated tuple:", new_tuple)
# Tuple unpacking
a, b, *rest = new_tuple
print("Unpacked elements:", a, b, rest)
11. WAP to create a tuple from two existing tuples using slicing.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2[1:] # Slicing to skip the first element of tuple2
print("Combined tuple:", combined_tuple)
12. WAP to create a set and demonstrate any four set methods.
my_set = {1, 2, 3, 4, 5}
# Add method
my_set.add(6)
print("Set after adding 6:", my_set)
# Remove method
my_set.remove(3)
print("Set after removing 3:", my_set)
# Intersection method
other_set = {4, 5, 6, 7, 8}
intersection = my_set.intersection(other_set)
print("Intersection of sets:", intersection)
# Clear method
my_set.clear()
print("Cleared set:", my_set)
13. WAP using set comprehension to create a set of multiples of 5 till 100.
multiples_of_5 = {x for x in range(1, 101) if x % 5 == 0}
print("Multiples of 5 till 100:", multiples_of_5)
14. WAP to create a dictionary and demonstrate any four dictionary methods.
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Get method
value = my_dict.get('b')
print("Value of 'b':", value)
# Keys method
keys = my_dict.keys()
print("Keys in dictionary:", keys)
# Values method
values = my_dict.values()
print("Values in dictionary:", values)
# Pop method
removed_value = my_dict.pop('b')
print("Dictionary after popping 'b':", my_dict)
15. WAP to combine values of two dictionaries having similar keys and create a new dictionary.
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 3, 'c': 4, 'd': 5}
unique_values = set(my_dict.values())
print("Unique values in dictionary:", unique_values)
# Upper method
upper_case = my_string.upper()
print("Uppercase:", upper_case)
# Lower method
lower_case = my_string.lower()
print("Lowercase:", lower_case)
# Split method
splitted = my_string.split(", ")
print("Splitted string:", splitted)
# Replace method
replaced = my_string.replace("World", "Python")
print("Replaced string:", replaced)
# Example usage
my_string = "Hello, World!"
print("Number of vowels:", count_vowels(my_string))
# Example usage
my_string = "hello"
print("Least frequency character:", least_frequency_char(my_string))
def outer_function():
# Enclosing variable
enclosing_var = "Enclosing"
def inner_function():
# Local variable
local_var = "Local"
print("Inside inner_function:", local_var, enclosing_var, global_var)
inner_function()
print("Inside outer_function:", enclosing_var, global_var)
outer_function()
print("Outside any function:", global_var)
22. WAP to demonstrate user defined functions with default arguments.
def greet(name="Guest"):
print("Hello,", name)
greet("Alice")
greet()
greet(name="Alice", message="Hi")
greet()
greet(message="Goodbye")
24. WAP with function that takes a number as parameter and checks if it is prime or not.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Example usage
number = 17
print(number, "is prime?", is_prime(number))
# Example usage
number = 5
print("Factorial of", number, "is", factorial(number))
26. WAP with function to calculate the number of uppercase and lowercase characters in given string.
def count_case(string):
upper_count = sum(1 for char in string if char.isupper())
lower_count = sum(1 for char in string if char.islower())
return upper_count, lower_count
# Example usage
my_string = "Hello, World!"
upper, lower = count_case(my_string)
print("Uppercase count:", upper)
print("Lowercase count:", lower)
27. WAP with function to find the smallest and largest word in a given string.
def min_max_word(string):
words = string.split()
min_word = min(words, key=len)
max_word = max(words, key=len)
return min_word, max_word
# Example usage
my_string = "This is a test string"
min_word, max_word = min_max_word(my_string)
print("Smallest word:", min_word)
print("Largest word:", max_word)
28. WAP to access and demonstrate any four functions of math module.
import math
# Square root
print("Square root of 16:", math.sqrt(16))
# Trigonometric functions
print("Sine of 30 degrees:", math.sin(math.radians(30)))
print("Cosine of 60 degrees:", math.cos(math.radians(60)))
# Logarithmic functions
print("Natural logarithm of 10:", math.log(10))
print("Base 2 logarithm of 8:", math.log2(8))
29. WAP to access and demonstrate four functions of any built-in Python module.
import random
# Shuffling a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print("Shuffled list:", my_list)
# def greet(name):
# print("Hello,", name)
# def farewell(name):
# print("Goodbye,", name)
import my_module
my_module.greet("Alice")
my_module.farewell("Bob")
mymodule.greet("Alice")
print(MyClass.attribute)
obj = MyClass()
obj.my_method()
obj = MyClass()
# This will raise an AttributeError
print(obj.__hidden_attribute)
35. WAP to demonstrate method overriding.
class ParentClass:
def my_method(self):
print("Parent method")
class ChildClass(ParentClass):
def my_method(self):
print("Child method")
child_obj = ChildClass()
child_obj.my_method()
class Parent2:
def method2(self):
print("Method of parent 2")
child_obj = Child()
child_obj.method1()
child_obj.method2()
class Parent(Grandparent):
def method2(self):
print("Method of parent")
class Child(Parent):
def method3(self):
print("Method of child")
child_obj = Child()
child_obj.method1()
child_obj.method2()
child_obj.method3()
38. WAP to open a file in append mode, write data to it and then read it.
with open("example.txt", "a") as file:
file.write("Hello, World!\n")
39. WAP to read contents of file1.txt and write the same to file2.txt.
with open("file1.txt", "r") as file1:
with open("file2.txt", "w") as file2:
file2.write(file1.read())