1.
Check Perfect Number
• A perfect number is a number that is equal to the sum of its positive divisors
(excluding itself). Write a program to check if a number is perfect.
def check_perfect_number(num):
divisors = [i for i in range(1, num) if num % i == 0]
if sum(divisors) == num:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
check_perfect_number(6)
1. Compute GCD
• Implement the Euclidean algorithm to find the GCD (Greatest Common Divisor)
of two numbers using a while loop.
def compute_gcd(a, b):
while b:
a, b = b, a % b
return a
print(compute_gcd(56, 98))
1. Compute LCM
• Write a Python function to compute the LCM (Least Common Multiple) of two
numbers, leveraging the GCD.
def compute_lcm(a, b):
gcd = compute_gcd(a, b)
return abs(a * b) // gcd
print(compute_lcm(12, 15))
1. Count Words
• Write a program to count the number of words in a user-input string (words are
separated by spaces).
def count_words(string):
words = string.split()
print(f"Number of words: {len(words)}")
count_words("This is a test string.")
1. Check Armstrong Number
• Write a function to check if a 3-digit number is an Armstrong number (e.g., 153 -
> 1^3 + 5^3 + 3^3 = 153).
def check_armstrong_number(num):
digits = [int(digit) for digit in str(num)]
sum_of_powers = sum([digit**3 for digit in digits])
if sum_of_powers == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
check_armstrong_number(153)
1. Sum of Series
• Write a Python program to calculate the sum of the series 1 + 1/2 + 1/3 + … + 1/n
using a for loop.
def sum_of_series(n):
total = sum(1 / i for i in range(1, n + 1))
print(f"Sum of series: {total}")
sum_of_series(5)
1. Generate Prime Numbers
• Write a program that generates all prime numbers in a given range [start, end].
def generate_prime_numbers(start, end):
primes = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
print(f"Prime numbers between {start} and {end}: {primes}")
generate_prime_numbers(10, 50)
1. Collatz Sequence
• Write a program that displays the Collatz sequence for any positive integer
given by the user.
def collatz_sequence(n):
while n != 1:
print(n, end=" -> ")
if n % 2 == 0:
n //= 2
else:
n=3*n+1
print(n)
collatz_sequence(7)
1. Diamond Pattern
• Print a diamond-shaped pattern of stars with a width given by the user (e.g.,
for 5).
def diamond_pattern(width):
for i in range(1, width + 1, 2):
print(" " * ((width - i) // 2) + "*" * i)
for i in range(width - 2, 0, -2):
print(" " * ((width - i) // 2) + "*" * i)
diamond_pattern(5)
1. FizzBuzz
• Print the numbers from 1 to n. For multiples of 3, print “Fizz” instead of the
number; for multiples of 5, print “Buzz”; for multiples of both 3 and 5, print
“FizzBuzz”.
def fizz_buzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizz_buzz(15)
1. Count Occurrences of Character
• Write a program to count how many times a specific character appears in a
given string.
def count_occurrences(string, char):
count = string.count(char)
print(f"The character '{char}' appears {count} times.")
count_occurrences("hello world", "o")
3. Lists & Tuples
1. List of Squares
• Write a list comprehension that generates a list of squares of numbers from 1
to 10.
squares = [x**2 for x in range(1, 11)]
print(squares)
1. Sum of List
• Write a program that calculates the sum of all elements in a list.
def sum_of_list(lst):
return sum(lst)
my_list = [1, 2, 3, 4, 5]
print(sum_of_list(my_list))
1. Largest & Smallest in List
• Write a function that returns the largest and the smallest elements in a given
list.
def find_largest_smallest(lst):
return max(lst), min(lst)
my_list = [12, 5, 18, 7, 34]
largest, smallest = find_largest_smallest(my_list)
print(f"Largest: {largest}, Smallest: {smallest}")
1. Remove Duplicates
• Write a Python function that removes duplicate elements from a list and
returns the new list.
def remove_duplicates(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(my_list))
1. Linear Search
• Implement a linear search to find a given element in a list. Return the index if
found, or -1 otherwise.
def linear_search(lst, target):
for index, element in enumerate(lst):
if element == target:
return index
return -1
my_list = [3, 6, 2, 9, 5]
print(linear_search(my_list, 9))
print(linear_search(my_list, 7))
1. Bubble Sort
• Implement the bubble sort algorithm to sort a list in ascending order.
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
my_list = [5, 3, 8, 6, 2]
print(bubble_sort(my_list))
1. List Reversal
• Write a program to reverse a list in-place (without using reversed() or slicing).
def list_reversal(lst):
for i in range(len(lst) // 2):
lst[i], lst[len(lst) - 1 - i] = lst[len(lst) - 1 - i], lst[i]
my_list = [1, 2, 3, 4, 5]
list_reversal(my_list)
print(my_list)
1. Count Occurrences in List
• Write a Python program that counts the number of times a given element
appears in a list.
def count_occurrences(lst, element):
return lst.count(element)
my_list = [1, 2, 3, 1, 1, 4]
print(count_occurrences(my_list, 1))
1. Rotate List
• Write a function to rotate a list by k positions to the right. For instance,
[1,2,3,4,5] rotated by 2 becomes [4,5,1,2,3].
def rotate_list(lst, k):
k = k % len(lst)
return lst[-k:] + lst[:-k]
my_list = [1, 2, 3, 4, 5]
print(rotate_list(my_list, 2))
1. Second Largest
• Write a function to find the second-largest element in a list.
def second_largest(lst):
lst = list(set(lst))
lst.sort()
return lst[-2] if len(lst) > 1 else None
my_list = [5, 3, 8, 6, 2]
print(second_largest(my_list))
1. Merge Two Sorted Lists
• Write a function that merges two sorted lists into one sorted list.
def merge_sorted_lists(lst1, lst2):
return sorted(lst1 + lst2)
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(merge_sorted_lists(list1, list2))
1. Find Duplicates
• Given a list, write a Python function to find all duplicate elements.
def find_duplicates(lst):
duplicates = []
seen = set()
for item in lst:
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]
print(find_duplicates(my_list))
1. Remove Even Numbers
• Write a program to remove all even numbers from a list of integers.
def remove_even_numbers(lst):
return [x for x in lst if x % 2 != 0]
my_list = [1, 2, 3, 4, 5, 6]
print(remove_even_numbers(my_list))
1. In-Place Shuffle
• Write a program to shuffle a list in-place (you can use random.shuffle or
implement your own shuffling algorithm).
import random
def in_place_shuffle(lst):
random.shuffle(lst)
return lst
my_list = [1, 2, 3, 4, 5]
print(in_place_shuffle(my_list))
1. Check Sorted
• Write a Python function to check if a given list is sorted in ascending order.
def check_sorted(lst):
return lst == sorted(lst)
my_list = [1, 2, 3, 4, 5]
print(check_sorted(my_list))
4. Dictionaries & Sets
1. Dict from Two Lists
• Given two lists of the same length, create a dictionary mapping elements of
one list to the corresponding elements of the other.
def dict_from_two_lists(keys, values):
return dict(zip(keys, values))
keys = ['a', 'b', 'c']
values = [1, 2, 3]
print(dict_from_two_lists(keys, values))
1. Frequency Count
• Write a program that counts the frequency of each element in a list using a
dictionary.
def frequency_count(lst):
freq = {}
for item in lst:
freq[item] = freq.get(item, 0) + 1
return freq
my_list = [1, 2, 2, 3, 3, 3, 4]
print(frequency_count(my_list))
1. Invert Dictionary
• Write a function that inverts a dictionary (keys become values, values become
keys).
def invert_dictionary(d):
return {v: k for k, v in d.items()}
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(invert_dictionary(my_dict))
1. Check Key Existence
• Write a program to check if a given key exists in a dictionary.
def check_key_existence(d, key):
return key in d
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(check_key_existence(my_dict, 'b'))
print(check_key_existence(my_dict, 'd'))
1. Dictionary Merge
• Write a function to merge two dictionaries. If a key appears in both, add their
values.
def dictionary_merge(d1, d2):
merged = d1.copy()
for key, value in d2.items():
merged[key] = merged.get(key, 0) + value
return merged
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
print(dictionary_merge(dict1, dict2))
1. Sort Dictionary by Value
• Write a Python program to sort a dictionary by its values in ascending order.
def sort_dict_by_value(d):
return dict(sorted(d.items(), key=lambda item: item[1]))
my_dict = {'a': 3, 'b': 1, 'c': 2}
print(sort_dict_by_value(my_dict))
1. Generate Dictionary
• Generate a dictionary that contains numbers (1 to n) as keys and their squares
as values.
def generate_dict(n):
return {i: i**2 for i in range(1, n+1)}
print(generate_dict(5))
1. Set Operations
• Write a Python program to perform union, intersection, and difference
operations on two sets.
def set_operations(set1, set2):
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2
return union, intersection, difference
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set_operations(set1, set2))
1. Unique Elements with Set
• Given a list with duplicates, use a set to create a list of unique elements (in any
order).
def unique_elements(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 4, 4, 5]
print(unique_elements(my_list))
1. Common Elements
• Given two lists, write a program to find the common elements using sets.
def common_elements(list1, list2):
return list(set(list1) & set(list2))
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print(common_elements(list1, list2))
5. Functions & Recursion
1. Recursive Factorial
• Implement a function factorial(n) that calculates n! using recursion.
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print(factorial(5))
1. Recursive Fibonacci
• Implement a function fib(n) to return the nth Fibonacci number using
recursion.
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(5))
1. Power Function
• Write a recursive function power(base, exp) that computes base^exp.
def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
print(power(2, 3))
1. Sum of List (Recursive)
• Write a recursive function that computes the sum of all elements in a list.
def sum_of_list(lst):
if not lst:
return 0
return lst[0] + sum_of_list(lst[1:])
my_list = [1, 2, 3, 4, 5]
print(sum_of_list(my_list))
Binary Search (Recursive)
• Implement binary search recursively to find an element in a
sorted list.
def binary_search_recursive(arr, target, low, high):
if low > high:
return -1
mid = low + (high - low) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search_recursive(arr, target, low, mid - 1)
else:
return binary_search_recursive(arr, target, mid + 1, high)
if __name__ == "__main__":
sorted_list = [2, 3, 5, 7, 11, 13, 17, 19, 23]
target = 11
result = binary_search_recursive(sorted_list, target, 0, len(sorted_list) - 1)
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")
1. Hanoi Towers
• Write a recursive solution to the Tower of Hanoi puzzle for n disks.
def tower_of_hanoi(n, source, target, auxiliary):
if n > 0:
tower_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, target, source)
tower_of_hanoi(3, 'A', 'C', 'B')
1. Count Vowels (Recursive)
• Write a recursive function that returns the number of vowels in a string.
def count_vowels(s):
return 0 if not s else (s[0].lower() in 'aeiou') + count_vowels(s[1:])
print(count_vowels("Recursive Function Example"))
1. Flatten Nested List (Recursive)
• Write a recursive function that takes a list which may contain nested lists and returns a flat
list of all elements.
def flatten_list(nested_list):
if not nested_list:
return []
if isinstance(nested_list[0], list):
return flatten_list(nested_list[0]) + flatten_list(nested_list[1:])
return [nested_list[0]] + flatten_list(nested_list[1:])
print(flatten_list([1, [2, [3, 4], 5], [6, 7], 8]))
1. Palindrome Check (Recursive)
• Write a recursive function that checks if a string is a palindrome.
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("lol"))
1. GCD (Recursive)
• Write a recursive function to compute the Greatest Common Divisor (GCD) of two numbers.
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(56, 98))
6. File I/O & Exception Handling
1. Read File
• Write a Python script that reads a text file and prints its contents.
def read_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
read_file('example.txt')
1. Write File
• Write a program that prompts the user for a line of text and writes that line to a file.
def write_to_file(file_name):
text = input("Enter a line of text: ")
with open(file_name, 'w') as file:
file.write(text)
write_to_file('output.txt')
1. Copy File
• Write a Python program to copy the contents of one file to another.
def copy_file(source_file, destination_file):
try:
with open(source_file, 'r') as src:
content = src.read()
with open(destination_file, 'w') as dest:
dest.write(content)
print(f"Content copied from {source_file} to {destination_file}")
except FileNotFoundError:
print(f"File {source_file} not found.")
except Exception as e:
print(f"An error occurred: {e}")
copy_file('source.txt', 'destination.txt')
1. Word Count in File
• Write a Python program that reads a file and counts the number of words in it.
def word_count_in_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
print(f"Number of words in {file_name}: {len(words)}")
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
word_count_in_file('example.txt')
1. Line Count
• Write a program that counts how many lines are in a file.
def line_count_in_file(file_name):
try:
with open(file_name, 'r') as file:
lines = file.readlines()
print(f"Number of lines in {file_name}: {len(lines)}")
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
line_count_in_file('example.txt')
1. Handle File Exceptions
• Modify the file-reading program to handle exceptions (e.g., file not found) gracefully.
def read_file_with_exception_handling(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except PermissionError:
print(f"Error: Permission denied to read the file '{file_name}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
read_file_with_exception_handling('example.txt')
1. Find Longest Word in File
• Write a program that finds the longest word in a text file and prints it.
def find_longest_word(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
longest_word = max(words, key=len)
print(f"The longest word in {file_name} is: {longest_word}")
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
find_longest_word('example.txt')
1. Search in File
• Write a program to search for a specific substring in a file and print the lines where it
appears.
def search_in_file(file_name, substring):
try:
with open(file_name, 'r') as file:
lines = file.readlines()
found = False
for line_num, line in enumerate(lines, 1):
if substring in line:
print(f"Line {line_num}: {line.strip()}")
found = True
if not found:
print(f"Substring '{substring}' not found in the file.")
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
search_in_file('example.txt', 'search_term')
1. Append to File
• Write a program that appends a user-input line to an existing file without overwriting it.
def append_to_file(file_name):
text = input("Enter a line to append to the file: ")
with open(file_name, 'a') as file:
file.write(text + '\n')
append_to_file('example.txt')
1. CSV Reader
• Write a Python script to read a CSV file and print each row.
import csv
def read_csv(file_name):
try:
with open(file_name, mode='r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
print(f"An error occurred: {e}")
read_csv('example.csv')
7. Object-Oriented Programming
1. Simple Class
• Define a class Person with attributes name and age. Create an instance of this class and
print its attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person('Alice', 30)
print(person.name, person.age)
1. Method in Class
• Add a method greet to the Person class that prints "Hello, my name is <name>".
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
person = Person('Alice', 30)
person.greet()
1. Constructor
• Define a class Car with a constructor that sets make, model, and year. Create an instance
and display its details.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_details(self):
print(f"{self.year} {self.make} {self.model}")
car = Car('Toyota', 'Corolla', 2020)
car.display_details()
1. Class with Default Values
• Modify the Car class to have default values for make and model if not provided.
class Car:
def __init__(self, make='Ford', model='Focus', year=2022):
self.make = make
self.model = model
self.year = year
def display_details(self):
print(f"{self.year} {self.make} {self.model}")
car = Car()
car.display_details()
1. Inheritance
• Create a base class Animal and a derived class Dog. The Dog class should inherit attributes
and methods from Animal.
class Animal:
def __init__(self, species):
self.species = species
def speak(self):
print(f"The {self.species} makes a sound.")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__('Dog')
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} the {self.breed} barks!")
dog = Dog('Buddy', 'Golden Retriever')
dog.speak()
dog.bark()
1. Method Overriding
• In the Dog class, override a method speak defined in Animal (e.g., Animal says “Some sound”,
but Dog says “Woof!”).
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak()
1. Multiple Classes
• Create classes Rectangle and Square. Square should inherit from Rectangle (or implement
composition) in a way that automatically sets the length and width to the same value.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
square = Square(5)
print(f"Area of square: {square.area()}")
1. Encapsulation
• Demonstrate encapsulation by creating a class with private attributes and use getter and
setter methods to access/modify them.
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
person = Person("Alice", 30)
print(person.get_name())
person.set_name("Bob")
print(person.get_name())
1. Polymorphism
• Demonstrate polymorphism by defining a method draw() in multiple classes (Circle, Triangle,
etc.) and calling draw() on a list of shapes.
class Circle:
def draw(self):
print("Drawing a circle")
class Triangle:
def draw(self):
print("Drawing a triangle")
class Square:
def draw(self):
print("Drawing a square")
shapes = [Circle(), Triangle(), Square()]
for shape in shapes:
shape.draw()
1. Class Method & Static Method
• Create a class Counter with a class variable count. Implement a @classmethod to increment
count and a @staticmethod to display some utility message.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
@staticmethod
def utility_message():
print("This is a utility method!")
Counter.increment()
print(Counter.count)
Counter.utility_message()
1. Magic Methods
• Implement a Python class that overloads the str method to return a string representation of
the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(Name: {self.name}, Age: {self.age})"
person = Person("Alice", 30)
print(person)
1. Operator Overloading
• Create a class Point that overloads the + operator (using add) to add the coordinates of two
Point objects.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2
print(result.x, result.y)
1. Abstract Class
• Use the abc module to define an abstract base class Shape with an abstract method area().
Implement subclasses Circle and Rectangle.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * 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
1. Property Decorator
• Create a class that uses the @property decorator to get/set an attribute with some
validation logic.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature cannot be below absolute zero!")
self._celsius = value
temp = Temperature(25)
print(temp.celsius)
temp.celsius = 30
print(temp.celsius)
1. Multiple Inheritance
Demonstrate multiple inheritance with two parent classes providing different
functionalities to a child class.
class Father:
def speak(self):
print("Father speaking")
class Mother:
def sing(self):
print("Mother singing")
class Child(Father, Mother):
pass
child = Child()
child.speak()
child.sing()
8. Modules & Libraries
1. Import Math Module
Write a script that uses the math module to compute the square root, floor, and ceiling of
a user-input number.
import math
def math_operations():
num = float(input("Enter a number: "))
print(f"Square root: {math.sqrt(num)}")
print(f"Floor: {math.floor(num)}")
print(f"Ceiling: {math.ceil(num)}")
math_operations()
1. Use Random Module
Write a function that randomly selects an element from a given list using the random
module.
import random
def random_element():
items = [1, 2, 3, 4, 5]
print(f"Random element: {random.choice(items)}")
random_element()
1. Use Datetime Module
Write a script that gets the current date and time and formats it as YYYY-MM-DD
HH:MM:SS.
import datetime
def current_datetime():
now = datetime.datetime.now()
print(f"Current date and time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
current_datetime()
1. Python OS Module
Write a program that lists all files and directories in the current directory using os.listdir().
import os
def list_files():
files = os.listdir()
print("Files and directories in the current directory:")
for file in files:
print(file)
list_files()
1. Statistics Module
Use the statistics module to compute the mean, median, and mode of a list of number
import statistics
def stats_operations():
numbers = [1, 2, 2, 3, 4, 5, 6]
print(f"Mean: {statistics.mean(numbers)}")
print(f"Median: {statistics.median(numbers)}")
print(f"Mode: {statistics.mode(numbers)}")
stats_operations()
1. Sys Module
Write a script that takes command-line arguments and prints them.
import sys
def print_arguments():
print("Command-line arguments:", sys.argv)
print_arguments()
1. Json Module
Write a script that reads a JSON file, modifies a value, and writes the updated data back
to the file.
import json
def modify_json():
with open('data.json', 'r') as file:
data = json.load(file)
data['key'] = 'new_value'
with open('data.json', 'w') as file:
json.dump(data, file, indent=4)
modify_json()
1. Requests Module
Write a program (assuming you have internet access) that fetches data from a public API
using the requests module and prints part of the JSON response.
import requests
def fetch_api_data():
url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(url)
data = response.json()
print(f"Title: {data['title']}")
fetch_api_data()
1. Regex Basics
Write a script that extracts all email addresses from a given string using the re module.
import re
def extract_emails():
text = "Here are some emails: test@example.com, hello@world.com"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print("Extracted emails:", emails)
extract_emails()
1. Logging
Write a script that uses the logging module to log debug, info, warning, and error
messages to a file.
import logging
def setup_logging():
logging.basicConfig(filename='app.log', level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
setup_logging()
9. Advanced Topics
1. List Slicing
Demonstrate advanced list slicing (e.g., reversing a list with slicing, skipping elements) in
a script.
def list_slicing():
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Reversed list:", my_list[::-1])
print("Every second element:", my_list[::2])
list_slicing()
1. Lambda & Map
Use a lambda function inside map to transform a list of numbers (e.g., multiply each by
2).
def lambda_map():
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, numbers))
print("Doubled numbers:", result)
lambda_map()
1. Filter & Reduce
Use filter to filter out even numbers from a list, then use functools.reduce to sum the
filtered numbers.
from functools import reduce
def filter_reduce():
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
sum_even = reduce(lambda x, y: x + y, even_numbers)
print("Sum of even numbers:", sum_even)
filter_reduce()
1. List vs Generator Comprehension
Write a script that demonstrates the difference between a list comprehension and a
generator expression for large data.
def list_vs_generator():
large_list = [x * 2 for x in range(1000000)] # List comprehension
large_gen = (x * 2 for x in range(1000000)) # Generator expression
print("List:", large_list[:5])
print("Generator:", list(large_gen)[:5])
list_vs_generator()
1. Decorators
Write a simple decorator timer that measures the execution time of a function.
import time
def timer_decorator(func):
def wrapper():
start_time = time.time()
func()
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
return wrapper
@timer_decorator
def example_function():
time.sleep(2)
example_function()
1. Context Manager
Implement a context manager using the with statement that opens a file, writes text, and
closes the file automatically.
class FileManager:
def __enter__(self):
self.file = open('example.txt', 'w')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager() as f:
f.write("Hello, world!")
1. Threading
Write a Python program that spawns two threads: one prints numbers 1 to 5, the other
prints letters A to E.
import threading
def print_numbers():
for i in range(1, 6):
print(i)
def print_letters():
for letter in ['A', 'B', 'C', 'D', 'E']:
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
1. Multiprocessing
Use the multiprocessing module to run a function in parallel processes and aggregate the
results.
import multiprocessing
def worker(number):
return number * 2
def run_in_parallel():
with multiprocessing.Pool(processes=4) as pool:
results = pool.map(worker, [1, 2, 3, 4])
print("Results:", results)
run_in_parallel()
1. Asyncio Basics
Write a simple asynchronous function using asyncio that prints a message, waits 1
second, and prints another message.
import asyncio
async def print_messages():
print("Message 1")
await asyncio.sleep(1)
print("Message 2")
asyncio.run(print_messages())
1. Exception Handling in Loops
Write a script that repeatedly asks the user for a number, catches ValueError if the input
is invalid, and stops when a valid number is entered.
def get_valid_number():
while True:
try:
num = int(input("Enter a number: "))
print(f"Valid number entered: {num}")
break
except ValueError:
print("Invalid input. Please enter a valid number.")
get_valid_number()