python
тЬЕ 1. Print “Hello, World!”
print("Hello, World!")
Output
Hello, World!
тЬЕ 2. Take input and display it
user_input = input("Enter something: ")
print("You entered:", user_input)
Sample Output
Enter something: Python
You entered: Python
тЬЕ 3. Add two numbers entered by the user
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum =", a + b)
Sample Output
Enter first number: 10
Enter second number: 20
Sum = 30.0
тЬЕ 4. Find square root of a number
import math
num = float(input("Enter a number: "))
print("Square Root =", math.sqrt(num))
Sample Output
Enter a number: 16
Square Root = 4.0
тЬЕ 5. Calculate factorial of a number
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial =", factorial)
Sample Output
Enter a number: 5
Factorial = 120
тЬЕ 6. Check if a number is prime
num = int(input("Enter a number: "))
if num <= 1:
print("Not a prime number")
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime number")
Sample Output
Enter a number: 11
Prime number
тЬЕ 7. Fibonacci sequence up to n terms
n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci Sequence:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Sample Output
Enter number of terms: 6
Fibonacci Sequence:
0 1 1 2 3 5
тЬЕ 8. Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Sample Output
Enter a number: 9
Odd number
тЬЕ 9. Check if a year is a leap year
year = int(input("Enter a year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a leap year")
Sample Output
Enter a year: 2024
Leap year
тЬЕ 10. Find the largest of three numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
if a >= b and a >= c:
print("Largest =", a)
elif b >= a and b >= c:
print("Largest =", b)
else:
print("Largest =", c)
Sample Output
Enter first number: 10
Enter second number: 25
Enter third number: 18
Largest = 25
тЬЕ 11. Check if a character is vowel or consonant
ch = input("Enter a character: ").lower()
if ch in 'aeiou':
print("Vowel")
else:
print("Consonant")
Sample Output
Enter a character: a
Vowel
тЬЕ 12. Print all prime numbers in a given range
start = int(input("Enter start: "))
end = int(input("Enter end: "))
print("Prime numbers:")
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
break
else:
print(num, end=" ")
Sample Output
Enter start: 10
Enter end: 25
Prime numbers:
11 13 17 19 23
тЬЕ 13. Reverse a number
num = int(input("Enter a number: "))
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
print("Reversed number =", rev)
Sample Output
Enter a number: 12345
Reversed number = 54321
тЬЕ 14. Check if a number is an Armstrong number
num = int(input("Enter a number: "))
temp = num
digits = len(str(num))
result = 0
while temp > 0:
digit = temp % 10
result += digit ** digits
temp //= 10
if result == num:
print("Armstrong number")
else:
print("Not an Armstrong number")
Sample Output
Enter a number: 153
Armstrong number
тЬЕ 15. Sum of all natural numbers up to n
n = int(input("Enter n: "))
total = n * (n + 1) // 2
print("Sum =", total)
Sample Output
Enter n: 10
Sum = 55
тЬЕ 16. Convert Celsius to Fahrenheit
c = float(input("Enter temperature in Celsius: "))
f = (c * 9/5) + 32
print("Fahrenheit:", f)
Sample Output
Enter temperature in Celsius: 37
Fahrenheit: 98.6
тЬЕ 17. Count number of vowels in a string
text = input("Enter a string: ").lower()
count = 0
for ch in text:
if ch in 'aeiou':
count += 1
print("Vowel count =", count)
Sample Output
Enter a string: Hello World
Vowel count = 3
тЬЕ 18. Reverse a string
text = input("Enter a string: ")
print("Reversed string:", text[::-1])
Sample Output
Enter a string: Python
Reversed string: nohtyP
тЬЕ 19. Check if a string is a palindrome
text = input("Enter a string: ").lower()
if text == text[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Sample Output
Enter a string: madam
Palindrome
тЬЕ 20. Remove punctuation from a string
import string
text = input("Enter a string: ")
clean = ""
for ch in text:
if ch not in string.punctuation:
clean += ch
print("String without punctuation:", clean)
Sample Output
Enter a string: Hello, world!!!
String without punctuation: Hello world
тЬЕ 21. Find the second largest number in a list
nums = [10, 25, 30, 45, 20]
unique_nums = list(set(nums))
unique_nums.sort()
print("Second largest number =", unique_nums[-2])
Sample Output
Second largest number = 30
тЬЕ 22. Remove duplicates from a list
nums = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(nums))
print("List without duplicates:", unique_list)
Sample Output
List without duplicates: [1, 2, 3, 4, 5]
тЬЕ 23. Sort a list of tuples by the second item
data = [(1, 3), (4, 1), (2, 2)]
sorted_data = sorted(data, key=lambda x: x[1])
print("Sorted list:", sorted_data)
Sample Output
Sorted list: [(4, 1), (2, 2), (1, 3)]
тЬЕ 24. Flatten a nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
print("Flattened list:", flat)
Sample Output
Flattened list: [1, 2, 3, 4, 5, 6]
тЬЕ 25. Merge two dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print("Merged dictionary:", merged)
Sample Output
Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
тЬЕ 26. Count frequency of elements in a list
nums = [1, 2, 2, 3, 3, 3]
freq = {}
for item in nums:
freq[item] = freq.get(item, 0) + 1
print("Frequency:", freq)
Sample Output
Frequency: {1: 1, 2: 2, 3: 3}
тЬЕ 27. Find the intersection of two lists
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
intersection = list(set(list1) & set(list2))
print("Intersection:", intersection)
Sample Output
Intersection: [3, 4]
тЬЕ 28. Rotate a list by k elements
nums = [1, 2, 3, 4, 5]
k = 2
k = k % len(nums)
rotated = nums[k:] + nums[:k]
print("Rotated list:", rotated)
Sample Output
Rotated list: [3, 4, 5, 1, 2]
тЬЕ 29. Implement binary search
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [10, 20, 30, 40, 50]
target = 30
result = binary_search(arr, target)
print("Element found at index:", result)
Sample Output
Element found at index: 2
тЬЕ 30. Find GCD of two numbers using recursion
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print("GCD =", gcd(48, 18))
Sample Output
GCD = 6
тЬЕ 31. Bubble Sort
arr = [5, 2, 9, 1, 5, 6]
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print("Sorted array:", arr)
Sample Output
Sorted array: [1, 2, 5, 5, 6, 9]
тЬЕ 32. Selection Sort
arr = [64, 25, 12, 22, 11]
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
print("Sorted array:", arr)
Sample Output
Sorted array: [11, 12, 22, 25, 64]
тЬЕ 33. Insertion Sort
arr = [12, 11, 13, 5, 6]
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print("Sorted array:", arr)
Sample Output
Sorted array: [5, 6, 11, 12, 13]
тЬЕ 34. Linear Search
arr = [10, 20, 30, 40, 50]
target = 30
found = -1
for i in range(len(arr)):
if arr[i] == target:
found = i
break
print("Element found at index:", found)
Sample Output
Element found at index: 2
тЬЕ 35. Longest Common Prefix
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if prefix == "":
return ""
return prefix
words = ["flower", "flow", "flight"]
print("Longest Common Prefix:", longest_common_prefix(words))
Sample Output
Longest Common Prefix: fl
тЬЕ 36. Group Anagrams
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
anagrams = {}
for word in words:
key = "".join(sorted(word))
anagrams.setdefault(key, []).append(word)
print("Grouped anagrams:", list(anagrams.values()))
Sample Output
Grouped anagrams: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
тЬЕ 37. Count the number of lines in a text file
(Assume file name: sample.txt)
with open("sample.txt", "r") as file:
lines = file.readlines()
print("Number of lines:", len(lines))
Sample Output
If sample.txt contains:
Hello
Python
World
Output:
Number of lines: 3
тЬЕ 38. Read a CSV file and display contents
(Assume file name: data.csv)
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Sample Output
If CSV contains:
Name,Age
John,25
Anna,22
Output:
['Name', 'Age']
['John', '25']
['Anna', '22']
тЬЕ 39. Write user input to a text file
text = input("Enter text: ")
with open("output.txt", "w") as file:
file.write(text)
print("Data written to output.txt")
Sample Output
Enter text: Hello Python
Data written to output.txt
тЬЕ 40. Count the number of words in a text file
(Assume file name: sample.txt)
with open("sample.txt", "r") as file:
text = file.read()
words = text.split()
print("Number of words:", len(words))
Sample Output
If file contains:
Python is fun
Output:
Number of words: 3
тЬЕ 41. Implement a Stack using a List
stack = []
# Push elements
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack:", stack)
# Pop element
print("Popped:", stack.pop())
print("Updated Stack:", stack)
Output
Stack: [10, 20, 30]
Popped: 30
Updated Stack: [10, 20]
тЬЕ 42. Implement a Queue using a List
queue = []
# Enqueue
queue.append(10)
queue.append(20)
queue.append(30)
print("Queue:", queue)
# Dequeue
print("Dequeued:", queue.pop(0))
print("Updated Queue:", queue)
Output
Queue: [10, 20, 30]
Dequeued: 10
Updated Queue: [20, 30]
тЬЕ 43. Implement a Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new = Node(data)
if not self.head:
self.head = new
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new
def display(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.append(30)
ll.display()
Output
10 -> 20 -> 30 -> None
тЬЕ 44. Reverse a Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
# Create list
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
# Reverse
new_head = reverse(head)
# Print reversed list
temp = new_head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
Output
3 -> 2 -> 1 -> None
тЬЕ 45. Detect a Cycle in Linked List (FloydтАЩs Algorithm)
class Node:
def __init__(self, data):
self.data = data
self.next = None
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# Create list with a cycle
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = head.next # cycle here
print("Cycle detected:", has_cycle(head))
Output
Cycle detected: True
тЬЕ 46. Find Middle of Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.data
# Create list
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
print("Middle element:", find_middle(head))
Output
Middle element: 30
тЬЕ 47. Merge Two Sorted Linked Lists
class Node:
def __init__(self, data):
self.data = data
self.next = None
def merge(l1, l2):
dummy = Node(0)
tail = dummy
while l1 and l2:
if l1.data < l2.data:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.next
# List1: 1 -> 3 -> 5
l1 = Node(1)
l1.next = Node(3)
l1.next.next = Node(5)
# List2: 2 -> 4 -> 6
l2 = Node(2)
l2.next = Node(4)
l2.next.next = Node(6)
# Merge
head = merge(l1, l2)
# Display
temp = head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
Output
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None
тЬЕ 48. Implement a Binary Tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Create tree
root = Node(10)
root.left = Node(5)
root.right = Node(15)
print("Root:", root.data)
print("Left Child:", root.left.data)
print("Right Child:", root.right.data)
Output
Root: 10
Left Child: 5
Right Child: 15
тЬЕ 49. In-order, Pre-order, Post-order Traversal
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root):
if root:
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
def preorder(root):
if root:
print(root.data, end=" ")
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.data, end=" ")
# Build tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
print("Inorder:", end=" "); inorder(root)
print("\nPreorder:", end=" "); preorder(root)
print("\nPostorder:", end=" "); postorder(root)
Output
Inorder: 2 1 3
Preorder: 1 2 3
Postorder: 2 3 1
тЬЕ 50. Implement a Binary Search Tree
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# Create BST
root = None
for num in [40, 20, 60, 10, 30, 50, 70]:
root = insert(root, num)
print("Inorder Traversal (sorted):")
inorder(root)
Output
Inorder Traversal (sorted):
10 20 30 40 50 60 70
тЬЕ 51. Height of a Binary Tree
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
# Test
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
print("Height of tree:", height(root))
Output
Height of tree: 3
тЬЕ 52. Graph Using Adjacency List
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": []
}
print("Adjacency List:")
for node, edges in graph.items():
print(node, "->", edges)
Output
Adjacency List:
A -> ['B', 'C']
B -> ['D']
C -> ['D']
D -> []
тЬЕ 53. Depth-First Search (DFS)
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["E"],
"D": [],
"E": []
}
visited = set()
def dfs(node):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(neighbour)
dfs("A")
Output
A B D C E
тЬЕ 54. Breadth-First Search (BFS)
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["E"],
"D": [],
"E": []
}
def bfs(start):
visited = set()
q = deque([start])
while q:
node = q.popleft()
if node not in visited:
print(node, end=" ")
visited.add(node)
q.extend(graph[node])
bfs("A")
Output
A B C D E
тЬЕ 55. Shortest Path in an Unweighted Graph (BFS)
from collections import deque
def shortest_path(graph, start, end):
q = deque([(start, [start])])
visited = set()
while q:
node, path = q.popleft()
if node == end:
return path
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
q.append((neighbor, path + [neighbor]))
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"],
"E": ["F"],
"F": []
}
print("Shortest path A тЖТ F:", shortest_path(graph, "A", "F"))
Output
Shortest path A тЖТ F: ['A', 'B', 'D', 'F']
тЬЕ 56. DijkstraтАЩs Algorithm
import heapq
def dijkstra(graph, start):
distances = {node: float("inf") for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, node = heapq.heappop(pq)
for neighbor, weight in graph[node]:
dist = current_distance + weight
if dist < distances[neighbor]:
distances[neighbor] = dist
heapq.heappush(pq, (dist, neighbor))
return distances
graph = {
"A": [("B", 1), ("C", 4)],
"B": [("D", 2)],
"C": [("D", 5)],
"D": []
}
print(dijkstra(graph, "A"))
Output
{'A': 0, 'B': 1, 'C': 4, 'D': 3}
тЬЕ 57. Longest Palindromic Substring
def longest_palindrome(s):
longest = ""
for i in range(len(s)):
for j in range(i, len(s)):
substr = s[i:j+1]
if substr == substr[::-1] and len(substr) > len(longest):
longest = substr
return longest
s = "babad"
print("Longest palindrome:", longest_palindrome(s))
Output
Longest palindrome: bab
тЬЕ 58. Longest Increasing Subsequence (LIS)
def lis(arr):
dp = [1] * len(arr)
for i in range(len(arr)):
for j in range(i):
if arr[j] < arr[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
arr = [10, 22, 9, 33, 21, 50]
print("Length of LIS:", lis(arr))
Output
Length of LIS: 4
тЬЕ 59. Quicksort Algorithm
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x <= pivot]
right = [x for x in arr[1:] if x > pivot]
return quicksort(left) + [pivot] + quicksort(right)
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted:", quicksort(arr))
Output
Sorted: [11, 12, 22, 25, 34, 64, 90]
тЬЕ 60. Merge Sort Algorithm
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
sorted_list = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_list.append(left[i])
i += 1
else:
sorted_list.append(right[j])
j += 1
sorted_list.extend(left[i:])
sorted_list.extend(right[j:])
return sorted_list
arr = [38, 27, 43, 3, 9, 82, 10]
print("Sorted:", merge_sort(arr))
Output
Sorted: [3, 9, 10, 27, 38, 43, 82]
тЬЕ 61. Decorator That Logs Function Calls
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with arguments {args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@logger
def add(a, b):
return a + b
print("Result:", add(5, 3))
Output
Calling add with arguments (5, 3) {}
Result: 8
тЬЕ 62. Decorator That Measures Execution Time
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} executed in {end - start:.6f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
slow_function()
Output
slow_function executed in 1.0002 seconds
тЬЕ 63. Generator That Yields Fibonacci Numbers
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fibonacci()
for _ in range(6):
print(next(gen), end=" ")
Output
0 1 1 2 3 5
тЬЕ 64. Generator to Read Large File Line by Line
(Using sample content instead of a real file)
def read_file_line_by_line(filename):
with open(filename, "r") as f:
for line in f:
yield line.strip()
# Create a sample file
with open("sample.txt", "w") as f:
f.write("Line 1\nLine 2\nLine 3")
for line in read_file_line_by_line("sample.txt"):
print(line)
Output
Line 1
Line 2
Line 3
тЬЕ 65. Using LRU Cache for Recursive Fibonacci
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(10))
Output
55
тЬЕ 66. Custom Context Manager Using __enter__ and __exit__
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("Opening file...")
self.file = open(self.filename, "w")
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing file...")
self.file.close()
with FileManager("test.txt") as f:
f.write("Hello World")
Output
Opening file...
Closing file...
тЬЕ 67. Custom Context Manager Using contextlib
from contextlib import contextmanager
@contextmanager
def open_file(name):
print("Opening file...")
f = open(name, "w")
try:
yield f
finally:
print("Closing file...")
f.close()
with open_file("test2.txt") as f:
f.write("Hello Again")
Output
Opening file...
Closing file...
тЬЕ 68. Count Word Frequencies Using collections.Counter
from collections import Counter
text = "apple orange apple banana apple orange"
words = text.split()
counter = Counter(words)
print(counter)
Output
Counter({'apple': 3, 'orange': 2, 'banana': 1})
тЬЕ 69. Using namedtuple to Represent a Point
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print("X =", p.x)
print("Y =", p.y)
Output
X = 3
Y = 4
тЬЕ 70. Using itertools.groupby() to Group Data
from itertools import groupby
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4), ("A", 5)]
# Sort by key first
data.sort(key=lambda x: x[0])
for key, group in groupby(data, key=lambda x: x[0]):
print(key, "->", list(group))
Output
A -> [('A', 1), ('A', 2), ('A', 5)]
B -> [('B', 3), ('B', 4)]
тЬЕ 71. Send Email Using smtplib
(Example ONLY тАФ requires real email/password + app-password)
import smtplib
from email.mime.text import MIMEText
def send_email():
sender = "you@example.com"
password = "your-password" # app-password recommended
receiver = "receiver@example.com"
msg = MIMEText("This is a test email sent from Python!")
msg["Subject"] = "Test Email"
msg["From"] = sender
msg["To"] = receiver
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender, password)
server.send_message(msg)
print("Email sent successfully!")
send_email()
Sample Output
Email sent successfully!
тЬЕ 72. Fetch Data from REST API Using requests
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
data = response.json()
print(data)
Output
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
тЬЕ 73. Parse JSON Data
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print("Name:", data["name"])
print("Age:", data["age"])
Output
Name: John
Age: 30
тЬЕ 74. Write Data to a JSON File
import json
data = {"name": "Alice", "age": 25, "city": "London"}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
print("Data written to data.json")
Output
Data written to data.json
тЬЕ 75. Web Scraping Using requests + BeautifulSoup
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
title = soup.find("h1").text
print("Page Title:", title)
Output
Page Title: Example Domain
тЬЕ 76. Rename Multiple Files in a Directory
import os
folder = "test_files"
files = os.listdir(folder)
for i, filename in enumerate(files):
new_name = f"file_{i}.txt"
os.rename(os.path.join(folder, filename), os.path.join(folder, new_name))
print("Files renamed successfully!")
Output
Files renamed successfully!
тЬЕ 77. Compress Multiple Files into a ZIP Archive
import zipfile
import os
files = ["file1.txt", "file2.txt", "file3.txt"]
with zipfile.ZipFile("archive.zip", "w") as zipf:
for f in files:
zipf.write(f)
print("Files compressed into archive.zip")
Output
Files compressed into archive.zip
тЬЕ 78. Extract Text from a PDF File
Requires:
pip install PyPDF2
import PyPDF2
with open("sample.pdf", "rb") as f:
reader = PyPDF2.PdfReader(f)
text = ""
for page in reader.pages:
text += page.extract_text()
print(text)
Output (example)
This is a sample PDF text.
тЬЕ 79. Automate File Backups
import shutil
import datetime
src = "important_file.txt"
backup_name = f"backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
shutil.copy(src, backup_name)
print("Backup created:", backup_name)
Output
Backup created: backup_20250215_141230.txt
тЬЕ 80. Validate Emails Using Regular Expressions
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
emails = ["test@example.com", "wrong-email@", "hello.world@gmail.com"]
for email in emails:
if re.match(pattern, email):
print(email, "-> Valid")
else:
print(email, "-> Invalid")
Output
test@example.com -> Valid
wrong-email@ -> Invalid
hello.world@gmail.com -> Valid
тЬЕ 81. Validate Phone Numbers Using Regex
(Format: 10-digit mobile number)
import re
pattern = r'^[6-9]\d{9}$'
phones = ["9876543210", "123456", "8123456789"]
for p in phones:
if re.match(pattern, p):
print(p, "-> Valid")
else:
print(p, "-> Invalid")
Output
9876543210 -> Valid
123456 -> Invalid
8123456789 -> Valid
тЬЕ 82. Extract URLs from Text
import re
text = "Check https://google.com and http://example.com for info."
urls = re.findall(r'https?://\S+', text)
print(urls)
Output
['https://google.com', 'http://example.com']
тЬЕ 83. Replace All Occurrences of a Word in a File
old = "hello"
new = "hi"
with open("sample.txt", "r") as f:
content = f.read()
content = content.replace(old, new)
with open("sample.txt", "w") as f:
f.write(content)
print("Replacement done!")
Output
Replacement done!
тЬЕ 84. Count Lines, Words, Characters in a File
with open("sample.txt", "r") as f:
text = f.read()
lines = text.count("\n") + 1
words = len(text.split())
chars = len(text)
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
Output
Lines: 3
Words: 12
Characters: 68
тЬЕ 85. Find Most Frequent Word in a Text File
from collections import Counter
with open("sample.txt", "r") as f:
words = f.read().split()
counter = Counter(words)
print("Most frequent word:", counter.most_common(1)[0])
Output
Most frequent word: ('hello', 4)
тЬЕ 86. Simple Calculator Using Classes
class Calculator:
def add(self, a, b): return a + b
def sub(self, a, b): return a - b
def mul(self, a, b): return a * b
def div(self, a, b): return a / b
calc = Calculator()
print("Add:", calc.add(5, 3))
print("Sub:", calc.sub(5, 3))
print("Mul:", calc.mul(5, 3))
print("Div:", calc.div(6, 3))
Output
Add: 8
Sub: 2
Mul: 15
Div: 2.0
тЪЩя╕П 87. Basic Command-Line Todo List
todo = []
while True:
choice = input("1.Add 2.View 3.Exit : ")
if choice == "1":
task = input("Enter task: ")
todo.append(task)
elif choice == "2":
print("Todo List:")
for t in todo:
print("-", t)
elif choice == "3":
break
Sample Run Output
1.Add 2.View 3.Exit : 1
Enter task: Buy milk
1.Add 2.View 3.Exit : 1
Enter task: Study Python
1.Add 2.View 3.Exit : 2
Todo List:
- Buy milk
- Study Python
тЬЕ 88. Basic HTTP Server Using http.server
from http.server import SimpleHTTPRequestHandler, HTTPServer
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print("Server running on http://localhost:8000")
server.serve_forever()
Output
Server running on http://localhost:8000
тЬЕ 89. Generate a Random Password
import random
import string
characters = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(characters) for _ in range(12))
print("Generated Password:", password)
Output
Generated Password: aG7@K2!mPq9&
тЬЕ 90. Password Strength Checker
Rules:
тЬФ 8+ chars
тЬФ Uppercase
тЬФ Lowercase
тЬФ Number
тЬФ Special char
import re
def password_strength(pwd):
if (len(pwd) >= 8
and re.search(r"[A-Z]", pwd)
and re.search(r"[a-z]", pwd)
and re.search(r"\d", pwd)
and re.search(r"[!@#$%^&*(),.?\":{}|<>]", pwd)):
return "Strong Password"
return "Weak Password"
print(password_strength("Hello123"))
print(password_strength("Hello@123"))
Output
Weak Password
Strong Password
тЬЕ 91. Maximum Subarray Sum (Kadane’s Algorithm)
def max_subarray(arr):
max_end = max_so_far = arr[0]
for x in arr[1:]:
max_end = max(x, max_end + x)
max_so_far = max(max_so_far, max_end)
return max_so_far
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum Subarray Sum:", max_subarray(arr))
Output
Maximum Subarray Sum: 6
тЬЕ 92. Longest Substring Without Repeating Characters
def longest_unique_substring(s):
seen = {}
start = max_len = 0
for i, ch in enumerate(s):
if ch in seen and seen[ch] >= start:
start = seen[ch] + 1
seen[ch] = i
max_len = max(max_len, i - start + 1)
return max_len
print(longest_unique_substring("abcabcbb"))
Output
3
тЬЕ 93. Two-Sum Problem
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
print(two_sum([2, 7, 11, 15], 9))
Output
[0, 1]
тЬЕ 94. Three-Sum Problem
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s == 0:
result.append([nums[i], nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
elif s < 0:
l += 1
else:
r -= 1
return result
print(three_sum([-1, 0, 1, 2, -1, -4]))
Output
[[-1, -1, 1], [-1, 0, 1]]
тЬЕ 95. Trie (Prefix Tree)
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.end = True
def search(self, word):
node = self.root
for ch in word:
if ch not in node.children:
return False
node = node.children[ch]
return node.end
trie = Trie()
trie.insert("apple")
print(trie.search("apple"))
print(trie.search("app"))
Output
True
False
тЬЕ 96. Serialize & Deserialize Binary Tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def serialize(root):
if not root:
return "None,"
return str(root.val) + "," + serialize(root.left) + serialize(root.right)
def deserialize(data):
values = iter(data.split(","))
def build():
val = next(values)
if val == "None":
return None
node = Node(int(val))
node.left = build()
node.right = build()
return node
return build()
root = Node(1)
root.left = Node(2)
root.right = Node(3)
data = serialize(root)
print("Serialized:", data)
new_root = deserialize(data)
print("Deserialized Root:", new_root.val)
Output
Serialized: 1,2,None,None,3,None,None,
Deserialized Root: 1
тЬЕ 97. Priority Queue Using a Heap
import heapq
pq = []
heapq.heappush(pq, 3)
heapq.heappush(pq, 1)
heapq.heappush(pq, 2)
while pq:
print(heapq.heappop(pq))
Output
1
2
3
тЬЕ 98. Sieve of Eratosthenes
def sieve(n):
nums = [True] * (n + 1)
nums[0] = nums[1] = False
for i in range(2, int(n**0.5) + 1):
if nums[i]:
for j in range(i*i, n+1, i):
nums[j] = False
return [i for i in range(n+1) if nums[i]]
print(sieve(30))
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
тЬЕ 99. Trie for Autocomplete
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.end = True
def autocomplete(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return []
node = node.children[ch]
result = []
def dfs(n, curr):
if n.end:
result.append(curr)
for c in n.children:
dfs(n.children[c], curr + c)
dfs(node, prefix)
return result
trie = Trie()
words = ["apple", "app", "apply", "apt", "bat"]
for w in words:
trie.insert(w)
print(trie.autocomplete("ap"))
Output
['app', 'apple', 'apply', 'apt']
тЬЕ 100. Basic LRU Cache
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.cap = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.cap:
self.cache.popitem(last=False)
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
cache.get(1)
cache.put(3, 3) # evicts key 2
print(cache.cache)
Output
OrderedDict([(1, 1), (3, 3)])
