PY
Python Cheat Sheet
A one-page reference for Python 3.12 and newer: syntax, data types, strings, loops, lists, dictionaries, functions, files and errors. Results after → show exactly what Python gives back.
Getting started Lesson
python --version | Shows the installed version (Windows: py --version) |
python | Opens the interactive shell; leave with exit() |
python hello.py | Runs a file (macOS/Linux often: python3 hello.py) |
print("Vanakkam") | Prints text → Vanakkam |
Syntax and variables Lesson
# a comment | Python ignores everything after # on the line |
if x > 0: | End with a colon, then indent the block 4 spaces |
city = "Madurai" | Create a variable; no type keyword needed |
total_price = 120 | Style: snake_case names |
MAX_SEATS = 40 | Constant by convention: CAPITALS |
a, b = 1, 2 | Assign several variables at once |
a, b = b, a | Swap two values |
print("a", "b", sep="-") | → a-b |
print("x", end="") | Prints without a line break at the end |
Data types Lesson
int, float, str, bool, None | Whole numbers, decimals, text, True/False, no value |
type(3.5) | → <class 'float'> |
isinstance(5, int) | → True |
int("42") | → 42 |
float("2.5") | → 2.5 |
str(99) | → '99' |
int("3.5") | ValueError: use float() first |
bool("") bool("0") | → False, True (only empty strings are falsy) |
0.1 + 0.2 | → 0.30000000000000004 (floats are approximate) |
0, 0.0, "", [], {}, None | Falsy values; almost everything else is truthy |
Strings Lesson
s = "Pondicherry" | Single or double quotes both work |
s[0] s[-1] | → 'P', 'y' (first and last character) |
s[0:4] | → 'Pond' (end index not included) |
s[::-1] | → 'yrrehcidnoP' |
len(s) | → 11 |
"chai".upper() | → 'CHAI' (also .lower(), .title()) |
" hi ".strip() | → 'hi' |
"a,b,c".split(",") | → ['a', 'b', 'c'] |
", ".join(["idli", "dosa"]) | → 'idli, dosa' |
"tea" in "masala tea" | → True |
f"{price:.2f}" | With price = 49.5 → '49.50' |
f"{1234567:,}" | → '1,234,567' |
Strings cannot be changed in place; methods like .replace() return a new string.
Operators Lesson
7 / 2 | → 3.5 (always a float) |
7 // 2 | → 3 (floor division) |
7 % 2 | → 1 (remainder) |
2 ** 10 | → 1024 (power) |
x += 1 | Short for x = x + 1 |
== != < > <= >= | Comparisons give True or False |
1 < x < 10 | Chained comparison: both must be true |
and or not | Logical operators, written as words |
3 in [1, 2, 3] | → True (membership) |
x is None | Use is to check for None |
Conditions Lesson
if marks >= 90: | Runs the indented block when true |
elif marks >= 50: | Checked only if the earlier tests failed |
else: | Runs when nothing above matched |
if items: | True when the list is not empty |
"big" if x > 3 else "small" | One-line conditional expression |
match status: | Compares one value against several patterns |
case 400 | 404: | Matches either value |
case _: | Wildcard: matches anything else |
pass | Placeholder for an empty block |
Loops Lesson
for city in cities: | Repeat once for each item |
range(5) | 0, 1, 2, 3, 4 (stop is not included) |
range(2, 10, 2) | 2, 4, 6, 8 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
while count < 3: | Repeat while the condition is true |
break continue | Leave the loop / skip to the next round |
for … else: | else runs only if the loop didn't break |
for i, c in enumerate(xs, start=1): | Index and item together |
for name, mark in zip(names, marks): | Loop over two lists side by side |
Lists and tuples Lesson
xs = ["a", "b", "c"] | A list: ordered and changeable |
xs.append("d") | Adds to the end |
xs.insert(0, "z") | Inserts at a position |
xs.pop() | Removes and returns the last item |
xs.remove("a") | Removes the first matching value |
sorted([3, 1, 2]) | → [1, 2, 3] (new list; original unchanged) |
xs.sort() | Sorts in place and returns None |
sum([3, 1, 2]), max([3, 1, 2]) | → 6, 3 |
[n * 2 for n in [1, 2, 3] if n > 1] | → [4, 6] (list comprehension) |
copy = xs.copy() | A real copy; copy = xs shares one list |
point = (3, 4) | A tuple: ordered but cannot be changed |
(1,) | A one-item tuple needs the comma |
Dictionaries and sets Lesson
d = {"name": "Ravi", "age": 30} | Key–value pairs |
d["city"] = "Salem" | Add or change a key |
d.get("phone", "-") | Default instead of a KeyError if missing |
"name" in d | → True (checks keys) |
for key, value in d.items(): | Loop over keys and values |
del d["age"] | Removes a key |
{n: n * n for n in range(3)} | → {0: 0, 1: 1, 2: 4} |
s = {1, 2, 3} | A set: unique items, no order |
set() | Empty set; {} is an empty dict |
{1, 2, 3} & {2, 3, 4} | → {2, 3} (also | union, - difference) |
Functions Lesson
def greet(name): | Define a function; indent its body below |
return f"Hi {name}" | Sends a value back to the caller |
def tax(amount, rate=0.18): | Default value for a parameter |
tax(rate=0.05, amount=200) | Keyword arguments, in any order |
def total(*prices): | Any number of positional arguments, as a tuple |
def profile(**info): | Any number of keyword arguments, as a dict |
return low, high | Returns a tuple: a, b = f() |
def area(w: float, h: float) -> float: | Type hints: documentation, not enforced |
lambda x: x * 2 | A tiny one-expression function |
sorted(["kiwi", "fig"], key=len) | → ['fig', 'kiwi'] |
A function without return returns None.
Files Lesson
with open("notes.txt", "w", encoding="utf-8") as f: | Opens for writing; closes automatically |
"r" "w" "a" | Read, write (replaces the file), append |
f.write("Hellon") | Writes text; add n yourself |
f.read() | The whole file as one string |
for line in f: | Reads one line at a time |
from pathlib import Path | Modern way to work with paths |
Path("notes.txt").read_text(encoding="utf-8") | Read a whole file in one line |
Path("notes.txt").exists() | → True or False |
csv.DictReader(f) | Each CSV row becomes a dict; open with newline="" |
json.dump(data, f, indent=2) | Save Python data as JSON |
json.load(f) | Read JSON back into Python data |
Modules and errors Lesson
import math | Then use math.sqrt(16) → 4.0 |
from math import ceil | Import one name directly |
import datetime as dt | Import with a shorter alias |
if __name__ == "__main__": | Runs only when the file is run directly |
python -m pip install requests | Installs a third-party package |
try: … except ValueError as e: | Catch a specific error |
else: / finally: | else if no error; finally always runs |
raise ValueError("Age must be positive") | Raise your own error |
ZeroDivisionError, KeyError, FileNotFoundError | Common built-in exceptions |
Catch only errors you expect; a bare except: hides real bugs.