Python Examples
Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.
Open the Try it Now editor »Python Introduction
Python Basics · 1 exampleprint("Hello, AgyanAdda!")
name = "Asha"
age = 21
print(f"{name} is {age} years old.")
for i in range(1, 4):
print("Line", i)
Output: Hello, AgyanAdda! Asha is 21 years old. Line 1 Line 2 Line 3
Python Installation
Python Basics · 1 example# Check the version (Windows)
python --version
# Python 3.13.0
# macOS / Linux
python3 --version
# Interactive shell
python
>>> 7 * 6
42
>>> "python".upper()
'PYTHON'
>>> exit()
# Run a file
python hello.py
If --version prints a Python 3 version, the installation works. Each line typed at >>> runs immediately.
Python Syntax and Comments
Python Basics · 1 example# Check if a student passed
marks = 72
if marks >= 40:
print("Passed") # inside the if block
if marks >= 75:
print("Distinction")
else:
print("Failed")
print("Result checked") # back outside the block
def area(length, width):
"""Return the area of a rectangle."""
return length * width
print(area(4, 5))
help(area)
Output: Passed, Result checked, 20, then help() shows "area(length, width) Return the area of a rectangle." Distinction is not printed because 72 < 75.
Python Variables
Python Basics · 1 examplename = "Ravi"
age = 25
height = 5.8
is_student = True
print(type(name), type(age), type(height), type(is_student))
# Multiple assignment and swapping
x, y = 10, 20
x, y = y, x
print("x =", x, "y =", y)
# Dynamic typing
value = 100
value = "one hundred"
print(value, type(value))
GST_RATE = 0.18 # constant by convention
print("Tax on 500:", 500 * GST_RATE)
Output: <class 'str'> <class 'int'> <class 'float'> <class 'bool'>, x = 20 y = 10, one hundred <class 'str'>, Tax on 500: 90.0
Python Data Types
Python Basics · 1 exampleitems = [10, "pen", 2.5, True, None, (1, 2), {"a": 1}]
for item in items:
print(repr(item), "->", type(item).__name__)
# Mutable list shared by two names
a = [1, 2, 3]
b = a
b.append(4)
print("a:", a) # a changed too!
c = a.copy() # independent copy
c.append(5)
print("a:", a, "c:", c)
print(isinstance(3.5, float))
print(bool(""), bool("0"), bool([]))
Lists each type name (int, str, float, bool, NoneType, tuple, dict). a becomes [1, 2, 3, 4] because b is the same list; the copy c is separate. Last line: False True False.
Python Numbers and Type Casting
Python Basics · 1 exampleimport math, random
from decimal import Decimal
price = "499"
qty = 3
total = int(price) * qty
print("Total:", total)
print(17 / 5, 17 // 5, 17 % 5, 2 ** 10)
print(round(3.14159, 2), math.sqrt(144), math.ceil(4.1))
print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2"))
print("Dice:", random.randint(1, 6))
print("Population:", f"{1_400_000_000:,}")
Output: Total: 1497, 3.4 3 2 1024, 3.14 12.0 5, 0.30000000000000004, 0.3, a random dice number, Population: 1,400,000,000
Python Strings
Python Basics · 1 exampletext = " learn python at agyanadda "
clean = text.strip().title()
print(clean) # Learn Python At Agyanadda
print(clean[0:5], clean[-9:]) # Learn Agyanadda
print(len(clean), clean.count("a"))
csv = "pen,book,bag"
items = csv.split(",")
print(items, " | ".join(items))
name, marks, total = "Asha", 436, 500
print(f"{name} scored {marks}/{total} = {marks / total:.1%}")
print(f"{'Item':<10}{'Price':>8}")
print(f"{'Laptop':<10}{54999:>8,}")
print("Python"[::-1], "py" in "python")
Prints the cleaned title, slices, the list ['pen', 'book', 'bag'] and 'pen | book | bag', "Asha scored 436/500 = 87.2%", an aligned table row "Laptop 54,999", and nohtyP True.
Python Operators
Python Basics · 1 examplea, b = 17, 5
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** 2)
age = 25
print(18 <= age < 60) # chained comparison
has_ticket, is_vip = True, False
print(has_ticket and not is_vip)
fruits = ["apple", "mango"]
print("mango" in fruits, "kiwi" not in fruits)
x = [1, 2]
y = [1, 2]
print(x == y, x is y) # equal values, different objects
count = 0
count += 5
print(count)
if (n := len(fruits)) >= 2:
print(f"{n} fruits")
Output: 22 12 85 3.4 3 2 289, True, True, True True, True False, 5, 2 fruits
Python Input and Output
Python Basics · 1 exampleitem = input("Item name: ")
price = float(input("Price: "))
qty = int(input("Quantity: "))
subtotal = price * qty
gst = subtotal * 0.18
print("-" * 30)
print(f"{'Item':<15}{item:>15}")
print(f"{'Subtotal':<15}{subtotal:>15.2f}")
print(f"{'GST 18%':<15}{gst:>15.2f}")
print(f"{'Total':<15}{subtotal + gst:>15.2f}")
print("-" * 30)
print("Thank", "you", sep="-", end="!\n")
Entering Pen, 20, 5 prints a neat receipt: Subtotal 100.00, GST 18% 18.00, Total 118.00, then Thank-you!
Python if, elif, else and match
Control Flow · 1 examplemarks = 82
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"
print("Grade:", grade)
result = "Pass" if marks >= 40 else "Fail"
print(result)
command = "stop"
match command:
case "start":
print("Starting...")
case "stop" | "exit":
print("Stopping...")
case _:
print("Unknown command")
Output: Grade: A, Pass, Stopping...
Python Loops: for and while
Control Flow · 1 examplestudents = ["Asha", "Ravi", "Neha"]
marks = [88, 64, 91]
for i, (name, m) in enumerate(zip(students, marks), start=1):
print(f"{i}. {name}: {m}")
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop after 7
print(n, end=" ")
print()
# while: guess game logic
secret, tries = 7, 0
for guess in [3, 9, 7]:
tries += 1
if guess == secret:
print(f"Found in {tries} tries")
break
else:
print("Not found")
count = 3
while count > 0:
print("Countdown:", count)
count -= 1
Prints a numbered list of students and marks, then 1 3 5 7, "Found in 3 tries", and a countdown 3, 2, 1.
Python Lists
Python Data Structures · 1 examplecart = ["milk", "bread"]
cart.append("eggs")
cart.insert(0, "rice")
cart.extend(["tea", "sugar"])
print(cart)
cart.remove("bread")
last = cart.pop()
print("Removed:", last, "| Now:", cart)
prices = [45, 120, 30, 250]
print(sorted(prices), sum(prices), max(prices))
prices.sort(reverse=True)
print("Top 2:", prices[:2])
names = ["Zoya", "amit", "Ravi"]
print(sorted(names, key=str.lower))
Shows the growing list, "Removed: sugar", the sorted prices [30, 45, 120, 250], total 445, max 250, Top 2: [250, 120], and names sorted ignoring case: ['amit', 'Ravi', 'Zoya'].
Python Tuples
Python Data Structures · 1 examplefrom collections import namedtuple
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = stats([72, 88, 95, 64])
print(f"Low {low}, High {high}, Avg {avg:.1f}")
student = ("Asha", 21, "Patna", "BCA")
name, age, *others = student
print(name, age, others)
single = (5,)
print(type(single), type((5)))
distances = {("Patna", "Delhi"): 1000}
print(distances[("Patna", "Delhi")])
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y, p)
Output: Low 64, High 95, Avg 79.8; Asha 21 ['Patna', 'BCA']; <class 'tuple'> <class 'int'>; 1000; 3 4 Point(x=3, y=4)
Python Sets
Python Data Structures · 1 examplepython_batch = {"Asha", "Ravi", "Neha", "Amit"}
web_batch = {"Ravi", "Zoya", "Amit"}
print("Both courses:", python_batch & web_batch)
print("Any course:", python_batch | web_batch)
print("Only Python:", python_batch - web_batch)
print("Exactly one:", python_batch ^ web_batch)
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique = set(emails)
print(len(emails), "->", len(unique))
blocked = {"spam@x.com"}
print("spam@x.com" in blocked)
print(type({}), type(set()))
Shows students in both courses {'Ravi', 'Amit'}, the union, Python-only students, and those in exactly one course (set order may vary). Then 5 -> 3, True, and <class 'dict'> <class 'set'>.
Python Dictionaries
Python Data Structures · 1 examplefrom collections import Counter
student = {"name": "Asha", "age": 21, "marks": {"math": 88, "physics": 76}}
print(student["name"], student.get("phone", "N/A"))
student["city"] = "Patna"
student["marks"]["chemistry"] = 91
for subject, mark in student["marks"].items():
print(f"{subject:<10}{mark}")
total = sum(student["marks"].values())
print("Total:", total)
words = "to be or not to be".split()
print(Counter(words).most_common(2))
defaults = {"theme": "light", "lang": "en"}
user = {"lang": "hi"}
print(defaults | user)
Prints Asha N/A, a table of subjects and marks including chemistry 91, Total: 255, [('to', 2), ('be', 2)], and {'theme': 'light', 'lang': 'hi'} — the user's value wins when merging.
Python List and Dictionary Comprehensions
Python Data Structures · 1 examplemarks = {"Asha": 88, "Ravi": 35, "Neha": 72, "Amit": 39}
passed = [name for name, m in marks.items() if m >= 40]
print("Passed:", passed)
results = {name: ("Pass" if m >= 40 else "Fail") for name, m in marks.items()}
print(results)
prices = ["₹120", "₹45", "₹300"]
numbers = [int(p.replace("₹", "")) for p in prices]
print(numbers, sum(numbers))
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat)
print(sum(n * n for n in range(1, 11)))
Output: Passed: ['Asha', 'Neha'], a dict of Pass/Fail per student, [120, 45, 300] 465, [1, 2, 3, 4, 5, 6], and 385.
Python Functions
Functions and Modules · 1 exampledef bill(*prices: float, discount: float = 0, **extra) -> float:
"""Return the total after discount, plus any extra charges."""
total = sum(prices) * (1 - discount / 100)
total += sum(extra.values())
return round(total, 2)
print(bill(100, 250, 50))
print(bill(100, 250, 50, discount=10))
print(bill(500, discount=5, delivery=40, packing=10))
def add_item(item, cart=None):
if cart is None: # safe default
cart = []
cart.append(item)
return cart
print(add_item("pen"), add_item("book"))
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([4, 9, 1])
print(lo, hi)
Output: 400, 360.0, 525.0, ['pen'] ['book'] (each call gets its own list), 1 9
Python Lambda, map, filter and sorted
Functions and Modules · 1 exampleproducts = [
{"name": "Laptop", "price": 54999, "rating": 4.5},
{"name": "Mouse", "price": 499, "rating": 4.1},
{"name": "Keyboard", "price": 1299, "rating": 4.7},
]
cheapest_first = sorted(products, key=lambda p: p["price"])
print([p["name"] for p in cheapest_first])
best = max(products, key=lambda p: p["rating"])
print("Best rated:", best["name"])
affordable = list(filter(lambda p: p["price"] < 2000, products))
print("Under 2000:", [p["name"] for p in affordable])
with_gst = list(map(lambda p: round(p["price"] * 1.18), products))
print(with_gst)
Output: ['Mouse', 'Keyboard', 'Laptop'], Best rated: Keyboard, Under 2000: ['Mouse', 'Keyboard'], [64899, 589, 1533]
Python Modules and Packages
Functions and Modules · 1 example# utils.py
def rupees(amount: float) -> str:
return f"₹{amount:,.2f}"
def gst(amount: float, rate: float = 18) -> float:
return round(amount * rate / 100, 2)
if __name__ == "__main__":
# runs only with: python utils.py
print("Testing:", rupees(1234.5), gst(1000))
# main.py
import statistics
from datetime import date
from utils import rupees, gst
sales = [1200, 3400, 2800, 4100]
print("Date:", date.today())
print("Average sale:", rupees(statistics.mean(sales)))
print("GST on 2800:", rupees(gst(2800)))
python main.py prints today's date, Average sale: ₹2,875.00 and GST on 2800: ₹504.00. The test line in utils.py does not run when it is imported.
Python pip and Virtual Environments
Functions and Modules · 1 examplemkdir weather-app && cd weather-app
# Create and activate a virtual environment
python -m venv .venv
.venv\Scripts\activate # Windows
# source .venv/bin/activate # macOS / Linux
(.venv) pip install requests python-dotenv
(.venv) pip list
# Save exact versions
(.venv) pip freeze > requirements.txt
# Later, on another machine:
pip install -r requirements.txt
(.venv) deactivate
Packages install only inside .venv for this project. requirements.txt lists them (e.g. requests==2.32.3) so anyone can recreate the same setup.
Python File Handling
Files and Exceptions · 1 exampleimport csv
from pathlib import Path
folder = Path("data")
folder.mkdir(exist_ok=True)
file = folder / "students.csv"
students = [
{"name": "Asha", "course": "BCA", "marks": 88},
{"name": "Ravi", "course": "MCA", "marks": 64},
]
with open(file, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "course", "marks"])
writer.writeheader()
writer.writerows(students)
with open(file, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(f"{row['name']:<6} {row['course']:<4} {row['marks']}")
log = folder / "log.txt"
with open(log, "a", encoding="utf-8") as f:
f.write("Report generated\n")
print(log.read_text(encoding="utf-8"))
Creates data/students.csv, prints each student on a line (Asha BCA 88, Ravi MCA 64), and appends a line to data/log.txt each time it runs.
Python Exception Handling
Files and Exceptions · 1 exampleclass InsufficientBalance(Exception):
pass
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > balance:
raise InsufficientBalance(f"Balance {balance} is less than {amount}")
return balance - amount
for attempt in ["abc", "-50", "5000", "300"]:
try:
amount = int(attempt)
balance = withdraw(1000, amount)
except ValueError as e:
print(f"{attempt!r}: invalid -> {e}")
except InsufficientBalance as e:
print(f"{attempt!r}: {e}")
else:
print(f"{attempt!r}: success, new balance {balance}")
finally:
print(" (transaction checked)")
'abc' gives an invalid literal error, '-50' gives Amount must be positive, '5000' gives Balance 1000 is less than 5000, and '300' succeeds with new balance 700. finally prints after every attempt.
Python Classes and Objects
Object-Oriented Python · 1 exampleclass BankAccount:
bank_name = "AgyanBank" # class attribute
def __init__(self, owner: str, balance: float = 0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
return self
def __str__(self):
return f"{self.owner}: ₹{self._balance:,.2f}"
asha = BankAccount("Asha", 1000)
ravi = BankAccount("Ravi")
asha.deposit(500).deposit(250)
ravi.deposit(2000)
print(asha)
print(ravi)
print(asha.balance, BankAccount.bank_name)
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
print(Product("Pen", 20))
Output: Asha: ₹1,750.00, Ravi: ₹2,000.00, 1750 AgyanBank, Product(name='Pen', price=20)
Python Inheritance and Polymorphism
Object-Oriented Python · 1 examplefrom abc import ABC, abstractmethod
import math
class Shape(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def area(self) -> float: ...
def describe(self):
return f"{self.name} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, w, h):
super().__init__("Rectangle")
self.w, self.h = w, h
def area(self):
return self.w * self.h
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
self.name = "Square"
class Circle(Shape):
def __init__(self, r):
super().__init__("Circle")
self.r = r
def area(self):
return math.pi * self.r ** 2
for shape in [Rectangle(4, 5), Square(3), Circle(2)]:
print(shape.describe())
print(isinstance(Square(2), Rectangle))
Output: Rectangle with area 20.00, Square with area 9.00, Circle with area 12.57, True. Trying Shape("x") would raise TypeError because Shape is abstract.
Python Iterators and Generators
Advanced Python · 1 exampleimport itertools
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(5)))
def fibonacci():
a, b = 0, 1
while True: # endless, but only computed on demand
yield a
a, b = b, a + b
print(list(itertools.islice(fibonacci(), 10)))
def read_large_log(lines):
for line in lines: # with a real file: for line in open(path)
if "ERROR" in line:
yield line.strip()
log = ["INFO start", "ERROR db down", "INFO retry", "ERROR timeout"]
for err in read_large_log(log):
print(err)
gen = countdown(2)
print(next(gen), next(gen))
print(list(itertools.combinations("ABC", 2)))
Output: [5, 4, 3, 2, 1], the first 10 Fibonacci numbers [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], the two ERROR lines, 2 1, and [('A', 'B'), ('A', 'C'), ('B', 'C')].
Python Decorators
Advanced Python · 1 exampleimport functools, time, random
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
def retry(times=3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError as e:
print(f"Attempt {attempt} failed: {e}")
raise ConnectionError("All attempts failed")
return wrapper
return decorator
@timer
def slow_sum(n):
return sum(range(n))
@retry(times=3)
def flaky_api():
if random.random() < 0.6:
raise ConnectionError("timeout")
return "data received"
print(slow_sum(5_000_000))
print(flaky_api())
@functools.cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
Prints the sum and how long it took (e.g. "slow_sum took 0.080s"), up to two failed attempts before "data received" (random, and it may fail all three times), and fib(80) = 23416728348467685 instantly thanks to caching.
Python Date and Time
Advanced Python · 1 examplefrom datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
today = date(2026, 12, 3)
due = today + timedelta(days=15)
print("Due:", due.strftime("%d %b %Y (%A)"))
exam = date(2027, 3, 1)
print("Days to exam:", (exam - today).days)
born = datetime.strptime("15-08-2004", "%d-%m-%Y").date()
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print("Age:", age)
meeting = datetime(2026, 12, 3, 17, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
print(meeting.isoformat())
print("London:", meeting.astimezone(ZoneInfo("Europe/London")).strftime("%I:%M %p"))
Output: Due: 18 Dec 2026 (Friday), Days to exam: 88, Age: 22, 2026-12-03T17:00:00+05:30, London: 11:30 AM
Python JSON
Advanced Python · 1 exampleimport json
from datetime import date
api_response = '{"user": {"name": "आशा", "active": true, "skills": ["Python", "SQL"], "phone": null}}'
data = json.loads(api_response)
print(data["user"]["name"], data["user"]["active"], data["user"]["phone"])
settings = {"theme": "dark", "font_size": 14, "updated": date(2026, 12, 3)}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False, default=str)
with open("settings.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded)
try:
json.loads("{'bad': 'quotes'}")
except json.JSONDecodeError as e:
print("Invalid JSON:", e.msg)
Output: आशा True None, then {'theme': 'dark', 'font_size': 14, 'updated': '2026-12-03'} (the date was saved as text), then Invalid JSON: Expecting property name enclosed in double quotes.
Python Regular Expressions
Advanced Python · 1 exampleimport re
mobile = re.compile(r"[6-9]\d{9}")
for m in ["9876543210", "1234567890", "98765"]:
print(m, "valid" if mobile.fullmatch(m) else "invalid")
text = "Contact asha@agyanadda.com or ravi.k@example.in by 25-12-2026."
print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))
date = re.search(r"(?P<d>\d{2})-(?P<m>\d{2})-(?P<y>\d{4})", text)
print(date["y"], date["m"], date["d"])
messy = "Learn Python at AgyanAdda"
print(re.sub(r"\s+", " ", messy))
print(re.sub(r"\d(?=\d{4})", "*", "9876543210"))
Output: 9876543210 valid, 1234567890 invalid, 98765 invalid; the two email addresses; 2026 12 25; "Learn Python at AgyanAdda"; and the masked number ******3210.
Python requests: Working with APIs
Advanced Python · 1 exampleimport os
import requests
BASE = "https://jsonplaceholder.typicode.com"
try:
r = requests.get(f"{BASE}/posts", params={"userId": 1}, timeout=10)
r.raise_for_status()
posts = r.json()
print(f"User 1 has {len(posts)} posts. First: {posts[0]['title'][:30]}...")
new = requests.post(
f"{BASE}/posts",
json={"title": "Hello", "body": "From Python", "userId": 1},
headers={"Authorization": f"Bearer {os.getenv('API_TOKEN', '')}"},
timeout=10,
)
print(new.status_code, new.json()["id"])
missing = requests.get(f"{BASE}/posts/99999", timeout=10)
missing.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTP error:", e.response.status_code)
except requests.exceptions.RequestException as e:
print("Network problem:", e)
Prints "User 1 has 10 posts. First: sunt aut facere...", then 201 101 for the created post, and finally HTTP error: 404 for the missing post.
Python with SQLite and MySQL Databases
Advanced Python · 1 exampleimport sqlite3
conn = sqlite3.connect("shop.db")
conn.row_factory = sqlite3.Row
with conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
stock INTEGER DEFAULT 0
)
""")
conn.execute("DELETE FROM products")
conn.executemany(
"INSERT INTO products (name, price, stock) VALUES (?, ?, ?)",
[("Pen", 20, 100), ("Notebook", 60, 40), ("Bag", 899, 5)],
)
conn.execute("UPDATE products SET stock = stock - ? WHERE name = ?", (2, "Bag"))
max_price = 100
for row in conn.execute("SELECT name, price, stock FROM products WHERE price < ? ORDER BY price", (max_price,)):
print(f"{row['name']:<10} ₹{row['price']:>6.2f} stock {row['stock']}")
total = conn.execute("SELECT SUM(price * stock) FROM products").fetchone()[0]
print("Stock value: ₹", total)
conn.close()
Creates shop.db, inserts three products, reduces Bag stock to 3, prints Pen and Notebook (under ₹100), and Stock value: ₹ 7097.0
Python Best Practices and Next Steps
Advanced Python · 1 example# calc.py
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger(__name__)
def emi(principal: float, annual_rate: float, months: int) -> float:
"""Monthly loan EMI."""
if months <= 0:
raise ValueError("months must be positive")
r = annual_rate / 12 / 100
if r == 0:
return round(principal / months, 2)
value = principal * r * (1 + r) ** months / ((1 + r) ** months - 1)
log.info("EMI for %s at %s%% over %s months = %.2f", principal, annual_rate, months, value)
return round(value, 2)
# test_calc.py (run: pytest)
import pytest
from calc import emi
def test_zero_interest():
assert emi(12000, 0, 12) == 1000
def test_known_value():
assert emi(100000, 12, 12) == pytest.approx(8884.88, abs=0.01)
def test_invalid_months():
with pytest.raises(ValueError):
emi(1000, 10, 0)
pytest runs three tests and reports 3 passed. The function has type hints, a docstring, input checks and logging instead of print.