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

PYTHON PRACTICALS AT

Ekdam faltu website ahe hi koni hi ithe yeun aapla time waste karu naye hi kind request ahe please

Uploaded by

aryannnborse2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PYTHON PRACTICALS AT

Ekdam faltu website ahe hi koni hi ithe yeun aapla time waste karu naye hi kind request ahe please

Uploaded by

aryannnborse2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1. WAP to display the sum of digits and reverse of a number.

def sum_and_reverse(num):
# Calculate sum of digits
digit_sum = sum(int(digit) for digit in str(num))

# Calculate reverse of the number


num_str = str(num)
num_reverse = int(num_str[::-1])

return digit_sum, num_reverse

# 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)

2. WAP to check if given number is palindrome or not.


def is_palindrome(num):
return str(num) == str(num)[::-1]

# Example usage
num = 12321
print("Is palindrome?", is_palindrome(num))

3. WAP to find sum of first 10 natural nos.


natural_numbers = range(1, 11)
sum_natural_numbers = sum(natural_numbers)
print("Sum of first 10 natural numbers:", sum_natural_numbers)
4. WAP to display n terms of the Fibonacci series.
def fibonacci(n):
fibonacci_sequence = [0, 1]
for i in range(2, n):
fibonacci_sequence.append(fibonacci_sequence[-1] + fibonacci_sequence[-2])
return fibonacci_sequence[:n]

# Example usage
n = 10
print("Fibonacci series:", fibonacci(n))

5. WAP to create a list and demonstrate any four list methods.


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

# 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}

combined_dict = {key: dict1[key] + dict2[key] for key in dict1.keys() & dict2.keys()}


print("Combined dictionary:", combined_dict)

16. WAP to sort a dictionary by values.


my_dict = {'b': 2, 'a': 1, 'c': 3}

sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}


print("Sorted dictionary by values:", sorted_dict)

17. WAP to find all unique values in a dictionary.


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

unique_values = set(my_dict.values())
print("Unique values in dictionary:", unique_values)

18. WAP to demonstrate four built in string functions.


my_string = "Hello, World!"

# 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)

19. WAP to count the number of vowels in the given string.


def count_vowels(string):
vowels = "aeiouAEIOU"
return sum(1 for char in string if char in vowels)

# Example usage
my_string = "Hello, World!"
print("Number of vowels:", count_vowels(my_string))

20. WAP to find the least frequency character in given string.


def least_frequency_char(string):
char_count = {}
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
least_freq_char = min(char_count, key=char_count.get)
return least_freq_char

# Example usage
my_string = "hello"
print("Least frequency character:", least_frequency_char(my_string))

21. WAP to demonstrate the L-E-G function scope in Python.


# Global variable
global_var = "Global"

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()

23. WAP to demonstrate user defined functions with keyword arguments.


def greet(name="Guest", message="Welcome"):
print(message, name)

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))

25. WAP with function to calculate the factorial of a given number.


def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

# 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

# Random number generation


print("Random integer between 1 and 100:", random.randint(1, 100))

# Random choice from a sequence


colors = ['red', 'green', 'blue', 'yellow']
print("Random color:", random.choice(colors))

# Shuffling a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print("Shuffled list:", my_list)

# Current date and time


import datetime
print("Current date and time:", datetime.datetime.now())

30. WAP to access methods of a user defined module.


# Let's assume we have a module named my_module.py
# with the following content:

# def greet(name):
# print("Hello,", name)

# def farewell(name):
# print("Goodbye,", name)

# Now, we can access its methods in another Python file:

import my_module

my_module.greet("Alice")
my_module.farewell("Bob")

31. WAP illustrating the use of user defined package in Python.


# Create a user-defined package named mypackage
# with a module named mymodule.py
# mypackage/mymodule.py
def greet(name):
print("Hello, {}!".format(name))

# In another Python file in the same directory


# import the package and use the module
# main.py
from mypackage import mymodule

mymodule.greet("Alice")

32. WAP to create a class and display class attributes.


class MyClass:
attribute = "Hello"

print(MyClass.attribute)

33. WAP to access object methods.


class MyClass:
def my_method(self):
print("Hello from my_method!")

obj = MyClass()
obj.my_method()

34. WAP to demonstrate data hiding.


class MyClass:
__hidden_attribute = "Hidden"

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()

36. WAP to demonstrate multiple inheritance.


class Parent1:
def method1(self):
print("Method of parent 1")

class Parent2:
def method2(self):
print("Method of parent 2")

class Child(Parent1, Parent2):


pass

child_obj = Child()
child_obj.method1()
child_obj.method2()

37. WAP to demonstrate multilevel inheritance.


class Grandparent:
def method1(self):
print("Method of grandparent")

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")

with open("example.txt", "r") as file:


print(file.read())

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())

40. WAP to raise the ZeroDivisionError exception.


x = 10
y=0
if y == 0:
raise ZeroDivisionError("Cannot divide by zero")
else:
result = x / y

You might also like