Exercise Questions and Answers
Here are various task-based exercises in Python across different topics, including Lists, Tuples, Sets, Dictionaries, Strings, DateTime, Math, and Classes/Objects.
Task Programs in Python
1. Find the Sum of Digits of a Number:
Write a program to find the sum of digits of a given number.
num = int(input("Enter a number: "))
sum_of_digits = 0
while num > 0:
sum_of_digits += num % 10
num //= 10
print(f"The sum of digits is: {sum_of_digits}")
List Exercises in Python
1. Reverse a List:
Write a program to reverse a given list.
lst = [1, 2, 3, 4, 5]
reversed_lst = lst[::-1]
print("Reversed list:", reversed_lst)
2. Find the Maximum and Minimum in a List:
lst = [10, 20, 4, 45, 99]
print("Maximum:", max(lst))
print("Minimum:", min(lst))
3. Remove Duplicates from a List:
lst = [1, 2, 3, 2, 1]
unique_lst = list(set(lst))
print("List without duplicates:", unique_lst)
Tuple Exercises in Python
1. Convert a Tuple to a List:
tuple_data = (1, 2, 3, 4)
list_data = list(tuple_data)
print("List:", list_data)
2. Find the Index of an Element in a Tuple:
tuple_data = (10, 20, 30, 40, 50)
index = tuple_data.index(30)
print("Index of 30:", index)
3. Concatenate Two Tuples:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print("Concatenated Tuple:", result)
Set Exercises in Python
1. Union of Two Sets:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1 | set2
print("Union of sets:", union_set)
2. Intersection of Two Sets:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1 & set2
print("Intersection of sets:", intersection_set)
3. Remove an Element from a Set:
set1 = {1, 2, 3, 4, 5}
set1.remove(3)
print("Set after removing 3:", set1)
Dictionary Exercises in Python
1. Add a Key-Value Pair to a Dictionary:
my_dict = {'name': 'John', 'age': 25}
my_dict['address'] = 'New York'
print("Updated Dictionary:", my_dict)
2. Merge Two Dictionaries:
dict1 = {'name': 'Alice', 'age': 22}
dict2 = {'address': 'Paris', 'job': 'Engineer'}
dict1.update(dict2)
print("Merged Dictionary:", dict1)
3. Check if a Key Exists in a Dictionary:
my_dict = {'name': 'John', 'age': 25}
if 'name' in my_dict:
print("Key 'name' exists in the dictionary.")
else:
print("Key 'name' does not exist.")
String Exercises in Python
1. Count Occurrences of a Substring:
my_string = "hello, hello world"
substring = "hello"
count = my_string.count(substring)
print(f"'{substring}' occurs {count} times.")
2. Check if a String is a Palindrome:
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
3. Convert a String to Title Case:
my_string = "hello world"
print("Title case:", my_string.title())
DateTime Exercises in Python
1. Get the Current Date and Time:
from datetime import datetime
current_datetime = datetime.now()
print("Current Date and Time:", current_datetime)
2. Format the Date:
from datetime import datetime
date = datetime.now()
formatted_date = date.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Date:", formatted_date)
3. Calculate the Difference Between Two Dates:
from datetime import datetime
date1 = datetime(2023, 5, 20)
date2 = datetime(2024, 5, 20)
difference = date2 - date1
print("Difference:", difference.days, "days")
Math Exercises in Python
1. Find the Square Root of a Number:
import math
num = int(input("Enter a number: "))
sqrt = math.sqrt(num)
print(f"The square root of {num} is {sqrt}")
2. Find the Factorial of a Number:
import math
num = int(input("Enter a number: "))
factorial = math.factorial(num)
print(f"The factorial of {num} is {factorial}")
3. Calculate the Power of a Number:
base = int(input("Enter base: "))
exponent = int(input("Enter exponent: "))
power = math.pow(base, exponent)
print(f"{base} raised to the power {exponent} is {power}")
Class and Object Exercises in Python
1. Create a Class with an __init__ Method:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
person = Person("Alice", 25)
person.display()
2. Create a Class with Class and Instance Methods:
class Employee:
company_name = "Tech Corp" # Class attribute
def __init__(self, name, salary):
self.name = name # Instance attribute
self.salary = salary
def display(self):
print(f"Employee Name: {self.name}, Salary: {self.salary}")
@classmethod
def company(cls):
print(f"Company: {cls.company_name}")
@staticmethod
def greet():
print("Hello, welcome to the company!")
employee = Employee("John", 50000)
employee.display()
employee.company()
employee.greet()
3. Inheritance Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Overriding method
These exercises cover a wide range of Python topics and will help you understand how different concepts work in practice. Let me know if you need more examples or further assistance! 😊
0 Comments