150 Basic Python Programs
150 Basic Python Programs
🔵 1. Fundamentals (01–15)
🎯 The absolute starting point. Every Python programmer writes these first.
01 — Hello World
print("Hello, World!")
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
03 — User Input
a, b = 10, 20
a, b = b, a
print(f"a={a}, b={b}")
06 — Multiple Assignment
x = y = z = 100
a, b, c = 1, 2, 3
print(x, y, z, a, b, c)
07 — Basic Arithmetic
a, b = 15, 4
print(a + b) # 19 addition
print(a - b) # 11 subtraction
print(a * b) # 60 multiplication
print(a / b) # 3.75 division
print(a // b) # 3 floor division
print(a % b) # 3 modulus
print(a ** b) # 50625 power
09 — Area of a Circle
import math
import math
r = float(input("Radius: "))
area = [Link] * r ** 2
print(f"Area = {area:.2f}")
11 — BMI Calculator
12 — Odd or Even
a, b, c = 10, 25, 18
largest = max(a, b, c)
print(f"Largest: {largest}")
n = int(input("n: "))
result = 1
for i in range(1, n + 1):
result *= i
print(f"{n}! = {result}")
17 — Factorial (recursion)
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
print(factorial(6)) # 720
18 — Fibonacci Series
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0: return False
import math
a, b = 48, 18
print(f"GCD = {[Link](a, b)}") # 6
import math
a, b = 4, 6
print(f"LCM = {[Link](a, b)}") # 12
23 — Sum of Digits
n = 12345
digit_sum = sum(int(d) for d in str(n))
print(f"Sum of digits: {digit_sum}") # 15
24 — Reverse a Number
n = 12345
reversed_n = int(str(n)[::-1])
print(reversed_n) # 54321
n = 121
print("Palindrome" if str(n) == str(n)[::-1] else "Not Pali
ndrome")
n = 153
digits = len(str(n))
print("Armstrong" if sum(int(d)**digits for d in str(n)) ==
n else "Not Armstrong")
n = 28
divisor_sum = sum(i for i in range(1, n) if n % i == 0)
print("Perfect" if divisor_sum == n else "Not Perfect") #
Perfect
n = 144
root = n ** 0.5
print(f"√{n} = {root}") # 12.0
n = 987654321
print(f"Digits: {len(str(abs(n)))}") # 9
s = "Hello World"
print(s[::-1]) # dlroW olleH
s = "racecar"
print("Palindrome" if s == s[::-1] else "Not Palindrome")
33 — Count Vowels
s = "Hello World"
vowels = sum(1 for c in [Link]() if c in "aeiou")
print(f"Vowels: {vowels}") # 3
35 — Check Anagram
s = "programming"
unique = "".join([Link](s))
s = "programming"
char = max(set(s), key=[Link])
print(f"Most frequent: '{char}' ({[Link](char)} times)")
39 — Caesar Cipher
s = "banana"
print([Link]("an")) # 2
43 — Remove Punctuation
def compress(s):
result, i = "", 0
while i < len(s):
count = 1
while i + count < len(s) and s[i] == s[i + count]:
count += 1
result += s[i] + (str(count) if count > 1 else "")
i += count
return result
print(compress("aaabbbcc")) # a3b3c2
nums = [1, 2, 2, 3, 4, 4, 5]
unique = list([Link](nums)) # preserves order
print(unique) # [1, 2, 3, 4, 5]
49 — Reverse a List
nums = [1, 2, 3, 4, 5]
print(nums[::-1]) # new reversed list
[Link]() # in-place
print(nums)
nums = [3, 1, 4, 1, 5, 9]
print(sorted(nums)) # ascending
print(sorted(nums, reverse=True)) # descending
52 — List Intersection
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
print(list(set(a) & set(b))) # [3, 4, 5]
53 — List Union
a = [1, 2, 3]
b = [3, 4, 5]
nums = [1, 2, 2, 3, 3, 3, 4]
from collections import Counter
print(Counter(nums)) # Counter({3:3, 2:2, 1:1, 4:1})
55 — Rotate a List
nums = [1, 2, 3, 4, 5]
n = 2
rotated = nums[n:] + nums[:n]
print(rotated) # [3, 4, 5, 1, 2]
60 — Matrix Addition
A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
C = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in
range(len(A))]
print(C) # [[6,8],[10,12]]
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = {**d1, **d2} # d2 values win on conflict
print(merged) # {'a':1, 'b':3, 'c':4}
63 — Invert a Dictionary
employee = {
"name": "Alice",
"address": {"city": "London", "zip": "EC1A"}
}
print(employee["address"]["city"]) # London
print([Link]("salary", "Not set"))
68 — Set Operations
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B) # union
print(A & B) # intersection
print(A - B) # difference
print(A ^ B) # symmetric difference
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
print([Link](B)) # True
print([Link](A)) # True
72 — Named Tuple
73 — OrderedDict
77 — Multiplication Table
n = 7
for i in range(1, 11):
print(f"{n} x {i:2} = {n*i:3}")
import random
secret = [Link](1, 100)
while True:
guess = int(input("Guess (1-100): "))
if guess < secret: print("Too low!")
elif guess > secret: print("Too high!")
else: print("Correct!"); break
for i in range(10):
if i == 3: continue # skip 3
if i == 7: break # stop at 7
print(i, end=" ") # 0 1 2 4 5 6
n = 5
while n > 0:
print(n)
n -= 1
else:
print("Loop complete")
85 — Ternary in Comprehension
command = "quit"
match command:
case "start": print("Starting...")
case "stop": print("Stopping...")
case "quit": print("Quitting...")
case _: print("Unknown command")
nums = [1, 3, 5, 7, 9]
target = 6
for n in nums:
if n == target:
print("Found!")
break
else:
print("Not found") # runs if loop completes without br
eak
import random
while (n := [Link](1, 10)) != 5:
print(f"Got {n}, not 5")
print("Got 5!")
⬛ 7. Functions (91–105)
🎯 Functions make code reusable and readable. These cover every function
pattern.
91 — Default Arguments
def stats(nums):
return min(nums), max(nums), sum(nums)/len(nums)
lo, hi, avg = stats([10, 20, 30, 40, 50])
print(f"Min:{lo} Max:{hi} Avg:{avg}")
94 — Lambda Functions
square = lambda x: x ** 2
add = lambda x, y: x + y
is_even = lambda x: x % 2 == 0
print(square(5), add(3,4), is_even(8))
96 — Closure
def multiplier(n):
def multiply(x):
return x * n
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5), triple(5)) # 10 15
97 — Decorator
@timer
def slow_sum(n):
return sum(range(n))
slow_sum(1000000)
@cache
def fib(n):
if n <= 1: return n
return fib(n-1) + fib(n-2)
print(fib(50)) # instant
99 — Generator Function
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(5):
print(x, end=" ") # 5 4 3 2 1
print(binary_search([1,3,5,7,9,11,13], 7)) # 3
def bubble_sort(arr):
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]
return arr
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
def merge_sort(arr):
if len(arr) <= 1: return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: [Link](left[i]); i
+= 1
else: [Link](right[j]); j
+= 1
return result + left[i:] + right[j:]
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self): [Link] = None
def append(self, data):
node = Node(data)
if not [Link]: [Link] = node; return
cur = [Link]
while [Link]: cur = [Link]
[Link] = node
def display(self):
vals, cur = [], [Link]
while cur: [Link]([Link]); cur = [Link]
print(" -> ".join(map(str, vals)))
ll = LinkedList()
with open("[Link]") as f:
lines = [Link]()
print(f"Lines: {len(lines)}")
import csv
with open("[Link]") as f:
reader = [Link](f)
for row in reader:
print(row)
import csv
rows = [{"name":"Alice","score":95},{"name":"Bob","score":8
7}]
with open("[Link]","w",newline="") as f:
writer = [Link](f, fieldnames=["name","score"])
[Link]()
[Link](rows)
import json
data = {"name":"Alice","scores":[95,87,91]}
with open("[Link]","w") as f:
[Link](data, f, indent=2)
with open("[Link]") as f:
loaded = [Link](f)
print(loaded)
import os
if [Link]("[Link]"):
print("File exists")
print(f"Size: {[Link]('[Link]')} bytes")
else:
print("File not found")
class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed
def bark(self):
return f"{[Link]} says: Woof!"
d = Dog("Buddy", "Labrador")
print([Link]())
class Counter:
count = 0 # shared by all instances
def __init__(self):
[Link] += 1
@classmethod
def get_count(cls):
return [Link]
118 — Inheritance
class Cat(Animal):
def speak(self): return f"{[Link]} says: Meow!"
class Dog(Animal):
def speak(self): return f"{[Link]} says: Woof!"
class Vector:
def __init__(self, x, y): self.x = x; self.y = y
def __add__(self, other): return Vector(self.x+other.x,
self.y+other.y)
def __repr__(self): return f"Vector({self.x}, {self.
y})"
def __len__(self): return int((self.x**2 + self.y**2)**
0.5)
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self): return self._radius
@[Link]
def radius(self, v):
if v < 0: raise ValueError("Radius cannot be negati
c = Circle(5)
print([Link]) # 78.53
[Link] = 10
print([Link]) # 314.15
class MathUtils:
@staticmethod
def is_even(n): return n % 2 == 0
@staticmethod
def clamp(val, lo, hi): return max(lo, min(val, hi))
print(MathUtils.is_even(4)) # True
print([Link](15, 0, 10)) # 10
122 — Dataclass
@dataclass
class Employee:
name: str
salary: float
skills: list = field(default_factory=list)
class Shape(ABC):
@abstractmethod
def area(self): pass
@abstractmethod
def perimeter(self): pass
class Rectangle(Shape):
def __init__(self, w, h): self.w = w; self.h = h
def area(self): return self.w * self.h
def perimeter(self): return 2 * (self.w + self.h)
r = Rectangle(4, 6)
print([Link](), [Link]()) # 24 20
class Timer:
import time
def __enter__(self):
import time; [Link] = [Link](); return self
def __exit__(self, *args):
import time; [Link] = [Link]() - [Link]
t
print(f"Elapsed: {[Link]:.4f}s")
with Timer():
total = sum(range(1000000))
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
import re
def is_valid_email(email):
pattern = r"^[\w.-]+@[\w.-]+\.\w{2,}$"
return bool([Link](pattern, email))
for e in ["alice@[Link]", "not-an-email", "user@.co
m"]:
print(f"{e}: {is_valid_email(e)}")
import re
def is_valid_url(url):
pattern = r"https?://[\w.-]+(?:\.[\w.-]+)+[\w._~:/?#\
[\]@!$&'()*+,;=-]*"
return bool([Link](pattern, url))
print(is_valid_url("[Link] # True
def to_roman(n):
vals = [(1000,'M'),(900,'CM'),(500,'D'),(400,'CD'),(10
0,'C'),(90,'XC'),
(50,'L'),(40,'XL'),(10,'X'),(9,'IX'),(5,'V'),
(4,'IV'),(1,'I')]
result = ""
for v, sym in vals:
while n >= v: result += sym; n -= v
return result
print(to_roman(2024)) # MMXXIV
n = 42
binary = bin(n)[2:] # '101010'
octal = oct(n)[2:] # '52'
hex_ = hex(n)[2:] # '2a'
print(binary, octal, hex_)
print(int(binary, 2)) # back to 42
import time
input("Press Enter to start...")
start = [Link]()
input("Press Enter to stop...")
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transposed = [list(row) for row in zip(*matrix)]
for row in transposed:
print(row)
def calculate(expr):
try: return eval(expr)
except: return "Invalid expression"
print(calculate("2 + 3 * 4")) # 14
print(calculate("100 / 4")) # 25.0
def rle_encode(s):
result, i = [], 0
while i < len(s):
count = 1
while i + count < len(s) and s[i] == s[i+count]: co
unt += 1
[Link]((s[i], count)); i += count
return result
print(rle_encode("AAABBBCCDDDDEE")) # [('A',3),('B',3),
('C',2),('D',4),('E',2)]
def is_palindrome(lst):
return lst == lst[::-1]
print(is_palindrome([1,2,3,2,1])) # True
print(is_palindrome([1,2,3,4,5])) # False
@retry(times=3, delay=0.5)
def flaky():
if [Link]() < 0.7: raise ValueError("Random fail
ure")
return "Success!"
@log
def add(a, b): return a + b
add(3, 4)
def memoize(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@memoize
def expensive(n):
print(f"Computing {n}...")
return n * n
print(expensive(5)) # Computing 5... 25
print(expensive(5)) # 25 (from cache)
import time
def progress_bar(total, width=40):
for i in range(total + 1):
done = int(width * i / total)
bar = "█" * done + "-" * (width - done)
print(f"\r[{bar}] {i}/{total}", end="", flush=True)
[Link](0.05)
print()
progress_bar(20)