Sure! Below are 15 Python tasks covering the specified topics, each accompanied by detailed solutions. These tasks range from basic to intermediate levels, providing a comprehensive understanding of Python programming concepts.
1. List Operations: Remove Duplicates
Task:
Given a list of integers, remove all duplicate elements and return a new list with unique elements while preserving the original order.
Solution:
def remove_duplicates(input_list):
seen = set()
unique_list = []
for item in input_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
return unique_list
# Example usage
numbers = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(numbers)) # Output: [1, 2, 3, 4, 5]
Explanation:
- Initialize an empty set
seen to track encountered elements.
- Iterate through each
item in input_list.
- If
item is not in seen, append it to unique_list and add it to seen.
- Return the
unique_list containing only unique elements in their original order.
2. Set Operations: Find Intersection
Task:
Given two sets of integers, find the intersection (common elements) between them.
Solution:
def find_intersection(set1, set2):
return set1.intersection(set2)
# Example usage
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(find_intersection(a, b)) # Output: {3, 4}
Explanation:
- Use the
intersection() method of sets to find common elements between set1 and set2.
- The result is a new set containing elements present in both sets.
3. String Operations: Reverse Words in a Sentence
Task:
Write a function that takes a sentence as input and returns the sentence with each word reversed, but the word order remains the same.
Solution:
def reverse_words(sentence):
words = sentence.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
# Example usage
sentence = "Hello World from Python"
print(reverse_words(sentence)) # Output: "olleH dlroW morf nohtyP"
Explanation:
- Split the sentence into words using
split().
- Reverse each word using slicing
word[::-1].
- Join the reversed words back into a sentence with spaces.
4. Dictionary Function: Count Word Frequencies
Task:
Given a list of words, count the frequency of each word and return a dictionary with words as keys and their frequencies as values.
Solution:
def count_frequencies(word_list):
frequency = {}
for word in word_list:
frequency[word] = frequency.get(word, 0) + 1
return frequency
# Example usage
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
print(count_frequencies(words))
# Output: {'apple': 3, 'banana': 2, 'orange': 1}
Explanation:
- Iterate through each
word in word_list.
- Use
get() to retrieve the current count of the word, defaulting to 0 if not found.
- Increment the count and update the
frequency dictionary.
5. Conditional Statement: Grade Calculator
Task:
Write a function that takes a numerical score (0-100) and returns the corresponding letter grade based on the following scale:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
Solution:
def calculate_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# Example usage
print(calculate_grade(85)) # Output: B
print(calculate_grade(72)) # Output: C
Explanation:
- Use a series of
if, elif, and else statements to determine the grade based on the score.
6. For Loop with Break: Find First Prime in a List
Task:
Given a list of integers, find and return the first prime number in the list. If no prime is found, return None.
Solution:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def first_prime(numbers):
for num in numbers:
if is_prime(num):
return num
return None
# Example usage
nums = [4, 6, 8, 9, 10, 11, 12]
print(first_prime(nums)) # Output: 11
Explanation:
- Define
is_prime to check if a number is prime.
- Iterate through
numbers using a for loop.
- Return the first number that is prime.
- If no prime is found, return
None.
7. While Loop with Continue: Print Even Numbers Until a Limit
Task:
Print all even numbers from 1 up to a given limit using a while loop. Use continue to skip odd numbers.
Solution:
def print_evens(limit):
num = 1
while num <= limit:
if num % 2 != 0:
num += 1
continue
print(num, end=' ')
num += 1
# Example usage
print_evens(10) # Output: 2 4 6 8 10
Explanation:
- Initialize
num to 1.
- Use a
while loop to iterate until num exceeds limit.
- If
num is odd, increment and continue to the next iteration.
- If
num is even, print it and increment.
8. Function: Fibonacci Sequence Generator
Task:
Write a function that returns the first n numbers in the Fibonacci sequence.
Solution:
def fibonacci(n):
seq = []
a, b = 0, 1
while len(seq) < n:
seq.append(a)
a, b = b, a + b
return seq
# Example usage
print(fibonacci(10))
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Explanation:
- Initialize two variables
a and b to 0 and 1.
- Use a
while loop to generate Fibonacci numbers until the sequence has n elements.
- Append
a to the sequence, then update a and b.
9. File Handling: Read and Count Lines in a Text File
Task:
Write a program to read a text file and count the number of lines it contains.
Solution:
def count_lines(file_path):
try:
with open(file_path, 'r') as file:
lines = file.readlines()
return len(lines)
except FileNotFoundError:
print("File not found.")
return 0
# Example usage
# Assuming 'sample.txt' exists with some content
print(count_lines('sample.txt')) # Output depends on 'sample.txt'
Explanation:
- Use
with open() to safely open the file in read mode.
- Read all lines using
readlines().
- Return the length of the list of lines.
- Handle
FileNotFoundError if the file does not exist.
10. File Handling: Write User Input to a Text File
Task:
Create a program that takes user input and writes it to a text file. The program should continue taking input until the user types 'exit'.
Solution:
def write_to_file(file_path):
with open(file_path, 'w') as file:
while True:
user_input = input("Enter text (type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
file.write(user_input + '\n')
# Example usage
# write_to_file('output.txt')
Explanation:
- Open the file in write mode using
with open().
- Continuously prompt the user for input.
- If the user types 'exit', break the loop.
- Otherwise, write the input to the file followed by a newline.
11. Object-Oriented Programming: Create a Simple Class
Task:
Define a Car class with attributes brand, model, and year. Add a method display_info() that prints the car’s information.
Solution:
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.brand} {self.model}")
# Example usage
my_car = Car("Toyota", "Corolla", 2020)
my_car.display_info() # Output: 2020 Toyota Corolla
Explanation:
- Define the
__init__ constructor to initialize brand, model, and year.
- Define
display_info to print the car’s details.
- Create an instance
my_car and call display_info().
12. Object-Oriented Programming: Inheritance
Task:
Create a base class Animal with a method make_sound(). Inherit from Animal to create a Dog class that overrides make_sound() to print "Bark!".
Solution:
class Animal:
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark!")
# Example usage
generic_animal = Animal()
generic_animal.make_sound() # Output: Some generic animal sound
my_dog = Dog()
my_dog.make_sound() # Output: Bark!
Explanation:
- Define
Animal with a generic make_sound method.
- Define
Dog that inherits from Animal and overrides make_sound.
- Instantiate both
Animal and Dog and call their respective make_sound methods.
13. Object-Oriented Programming: Encapsulation
Task:
Create a BankAccount class with a private attribute __balance. Implement methods to deposit, withdraw, and get_balance.
Solution:
class BankAccount:
def __init__(self, initial_balance=0):
self.__balance = initial_balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient funds.")
elif amount <= 0:
print("Withdrawal amount must be positive.")
else:
self.__balance -= amount
print(f"Withdrew {amount}. New balance: {self.__balance}")
def get_balance(self):
return self.__balance
# Example usage
account = BankAccount(100)
account.deposit(50) # Deposited 50. New balance: 150
account.withdraw(30) # Withdrew 30. New balance: 120
print(account.get_balance()) # Output: 120
Explanation:
- Use double underscores
__balance to make the attribute private.
- Provide public methods
deposit, withdraw, and get_balance to interact with the balance.
- Validate input amounts to ensure appropriate operations.
14. Object-Oriented Programming: Polymorphism
Task:
Demonstrate polymorphism by creating two classes Circle and Rectangle with a method area(). Calculate the area of different shapes using the same interface.
Solution:
import math
class Shape:
def area(self):
pass # To be overridden
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Example usage
shapes = [
Circle(5),
Rectangle(4, 6)
]
for shape in shapes:
print(f"Area: {shape.area()}")
# Output:
# Area: 78.53981633974483
# Area: 24
Explanation:
- Define a base class
Shape with a method area() to be overridden.
- Define
Circle and Rectangle classes that inherit from Shape and implement the area() method.
- Iterate through a list of shapes and call
area() on each, demonstrating polymorphism.
15. Combined Concepts: Student Record System
Task:
Create a Student class with attributes name, roll_number, and grades (a dictionary mapping subjects to scores). Implement methods to add a grade, calculate average grade, and display student information. Additionally, manage multiple students using a dictionary.
Solution:
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
self.grades = {}
def add_grade(self, subject, score):
self.grades[subject] = score
def average_grade(self):
if not self.grades:
return 0
total = sum(self.grades.values())
return total / len(self.grades)
def display_info(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.roll_number}")
print("Grades:")
for subject, score in self.grades.items():
print(f" {subject}: {score}")
print(f"Average Grade: {self.average_grade():.2f}")
# Manage multiple students using a dictionary
def manage_students():
students = {}
while True:
print("\n1. Add Student")
print("2. Add Grade")
print("3. Display Student Info")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
name = input("Enter student name: ")
roll = input("Enter roll number: ")
if roll in students:
print("Roll number already exists.")
else:
students[roll] = Student(name, roll)
print("Student added.")
elif choice == '2':
roll = input("Enter roll number: ")
if roll in students:
subject = input("Enter subject: ")
try:
score = float(input("Enter score: "))
students[roll].add_grade(subject, score)
print("Grade added.")
except ValueError:
print("Invalid score.")
else:
print("Student not found.")
elif choice == '3':
roll = input("Enter roll number: ")
if roll in students:
students[roll].display_info()
else:
print("Student not found.")
elif choice == '4':
print("Exiting.")
break
else:
print("Invalid option.")
# Example usage
# manage_students()
Explanation:
- Define a
Student class with name, roll_number, and grades.
- Implement methods to
add_grade, calculate average_grade, and display_info.
- Create a
manage_students function to handle multiple students using a dictionary where keys are roll_number and values are Student objects.
- Provide a simple menu-driven interface to add students, add grades, display student information, and exit.
Note:
To run the manage_students function, uncomment the last line in the code. This program will interactively prompt the user to manage student records.
These tasks and solutions cover various fundamental Python concepts, including data structures, control flow, functions, file handling, and object-oriented programming. Practicing these will enhance your understanding and proficiency in Python.