Cheat sheet

Python Cheat Sheet: Syntax, Commands and Built-in Functions in Tables

Updated: · Skillaria.Top

Python syntax is built on indentation instead of curly braces: the block after a colon is indented by 4 spaces. The basics are variables without type declarations, if/elif/else conditions, for and while loops, def functions, and built-in functions such as print, len, range, input and type, plus methods of strings, lists and dictionaries.

This Python cheat sheet gathers on one page everything you need to keep at hand during your first months: Python syntax, loops, built-in functions, string, list and dictionary methods, and terminal commands. Each table is a short reference with working examples you can paste straight into the REPL.

Python syntax basics

The main feature of the language is that blocks are defined by indentation, not by braces. After a line ending with a colon (if, for, def, class), the following lines are indented by 4 spaces. Do not mix tabs and spaces, or you will get an IndentationError.

ConstructExampleExplanation
Comment# texteverything from # to the end of the line is ignored
Variableage = 25no type is declared, the value determines it
Multiple assignmenta, b = 1, 2unpacking; swapping values: a, b = b, a
Outputprint("Hello", name)arguments are separated by a space
Inputs = input("Name: ")always returns a string
f-stringf"{name}: {price:.2f}"inserts expressions and applies formatting
Type annotationcount: int = 0a hint for IDEs and checkers, not checked at run time
Empty blockpassa placeholder where the syntax requires a body
Importfrom math import sqrtconnects a module or a name from it

Data types

TypeLiteralMutable
int42, 1_000_000no
float3.14, 1e-3no
boolTrue, Falseno
str"text", 'text', """many lines"""no
list[1, 2, 3]yes
tuple(1, 2), (1,)no
dict{"a": 1}yes
set{1, 2}, empty — set()yes
NoneTypeNone—

Operators

GroupOperatorsExample → result
Arithmetic+ - * / // % **7 // 2 → 3, 7 % 2 → 1, 2 ** 10 → 1024
Comparison== != < > <= >=1 < x < 10 — a chained comparison
Logicaland or notx or "default"
Membershipin, not in"a" in "abc" → True
Identityis, is notx is None
Assignment+= -= *= /=, :=if (n := len(s)) > 10: ...

Conditions and pattern matching

if score >= 90:
    grade = "A"
elif score >= 70:
    grade = "B"
else:
    grade = "C"

status = "adult" if age >= 18 else "minor"   # conditional expression

match command:
    case "start":
        print("Starting")
    case "stop" | "exit":
        print("Stopping")
    case _:
        print("Unknown command")

The following count as false: False, None, 0, the empty string and empty collections, so instead of if len(items) > 0 people simply write if items.

Python loops: for and while syntax

The for loop

The Python for loop syntax is for variable in sequence: followed by a body indented under it. The loop iterates over any iterable object: a string, a list, a dictionary, a file or a range.

for i in range(5):              # 0 1 2 3 4
    print(i)

for i in range(10, 0, -2):      # 10 8 6 4 2
    print(i)

for i, fruit in enumerate(["apple", "pear"], start=1):
    print(i, fruit)

for name, score in zip(names, scores):
    print(name, score)

for key, value in prices.items():
    print(key, value)

The while loop

attempts = 3
while attempts > 0:
    password = input("Password: ")
    if password == "secret":
        print("Logged in")
        break
    attempts -= 1
else:
    print("No attempts left")   # runs if the loop ended without break
CommandWhat it does
breakleaves the loop early
continuemoves on to the next iteration
else on a loopruns if the loop finished without break
range(stop), range(start, stop, step)a sequence of numbers, stop is not included

List comprehensions

squares = [x ** 2 for x in range(10)]
evens = [x for x in numbers if x % 2 == 0]
lengths = {word: len(word) for word in words}
unique = {c.lower() for c in text}
total = sum(x * x for x in range(100))   # generator expression

Functions

def greet(name: str, greeting: str = "Hello") -> str:
    """Returns a greeting."""
    return f"{greeting}, {name}!"

def total(*args, **kwargs):
    return sum(args), kwargs

square = lambda x: x * x
print(greet("Anna"))                 # Hello, Anna!
print(greet("Anna", greeting="Hi"))  # Hi, Anna!
ElementMeaning
def f(a, b=1)a parameter with a default value
*argsany number of positional arguments (a tuple)
**kwargsany number of named arguments (a dictionary)
returnreturns a value; without it the function returns None
lambda x: ...a short anonymous function with a single expression
global, nonlocalchange a variable from an outer scope

Do not use a mutable default value such as def f(items=[]): the list is created once and accumulates between calls. The correct way is items=None and, inside, if items is None: items = [].

Python built-in functions

Python built-in functions are available without any import. These are the core functions that appear in almost every script.

FunctionWhat it doesExample → result
print()prints valuesprint(1, 2, sep="-") → 1-2
input()reads a line from the keyboardint(input())
len()length of a collection or stringlen("abc") → 3
type()the type of an objecttype(3.0) → <class 'float'>
isinstance()checks the typeisinstance(5, int) → True
int() float() str() bool()type conversionint("42") → 42
list() tuple() set() dict()create collectionslist("ab") → ['a', 'b']
range()a range of numberslist(range(3)) → [0, 1, 2]
enumerate()pairs of (index, element)list(enumerate("ab")) → [(0, 'a'), (1, 'b')]
zip()pairs up sequences element by elementlist(zip([1, 2], "ab")) → [(1, 'a'), (2, 'b')]
sum() min() max()sum, minimum, maximummax([3, 7, 1]) → 7
abs() round()absolute value and roundinground(3.14159, 2) → 3.14
sorted()a new sorted listsorted(words, key=len, reverse=True)
reversed()an iterator in reverse orderlist(reversed([1, 2])) → [2, 1]
map() filter()apply a function / filterlist(map(str, [1, 2])) → ['1', '2']
any() all()at least one / all are trueall(x > 0 for x in nums)
open()opens a fileopen("a.txt", encoding="utf-8")
help() dir()help and a list of attributeshelp(str.split), dir(list)
id() hash()identity and hash of an objecthash("a")

The most convenient Python reference is always at hand: the help() function in the REPL. help(dict) shows all dictionary methods with descriptions, and dir(obj) lists the available names.

Python string methods

Python string basics: a string is immutable, and each method returns a new string. Slices work the same way as for lists: s[1:4], and s[::-1] reverses the string.

MethodExample → result
upper() lower()"Py".upper() → 'PY'
capitalize() title()"hello world".title() → 'Hello World'
strip() lstrip() rstrip()" hi \n".strip() → 'hi'
split(sep)"a,b,c".split(",") → ['a', 'b', 'c']
join(iterable)"-".join(["a", "b"]) → 'a-b'
replace(old, new)"cat".replace("c", "b") → 'bat'
find() index()"hello".find("l") → 2; if not found — -1 (index raises an error)
count()"banana".count("a") → 3
startswith() endswith()"file.py".endswith(".py") → True
isdigit() isalpha() isspace()"123".isdigit() → True
removeprefix() removesuffix()"test_a".removeprefix("test_") → 'a'
zfill() center() ljust()"7".zfill(3) → '007'
format()"{} + {}".format(1, 2) → '1 + 2'

Python list methods

A list is a mutable ordered collection. Most methods change the list in place and return None, so a = a.sort() is a common mistake.

OperationWhat it doesExample
append(x)adds to the enda.append(4)
extend(iter)adds all elementsa.extend([5, 6])
insert(i, x)inserts at an indexa.insert(0, "first")
remove(x)removes the first occurrence of a valuea.remove(3)
pop(i)removes and returns an element (the last one by default)last = a.pop()
clear()empties the lista.clear()
index(x)index of the first occurrencea.index("b")
count(x)number of occurrencesa.count(1)
sort()sorts in placea.sort(key=str.lower)
reverse()reverses in placea.reverse()
copy()shallow copyb = a.copy()
del a[i]deletes by index or slicedel a[1:3]
Slicesa[start:stop:step]a[-1] — the last one, a[:3] — the first three

Python dictionary methods

OperationWhat it doesExample
d[key]value by key, missing key — KeyErrord["name"]
get(key, default)the value, or a fallbackd.get("age", 0)
d[key] = valueadd or changed["city"] = "Boston"
keys() values() items()keys, values, pairsfor k, v in d.items():
update()merge with another dictionaryd.update({"a": 1})
d1 | d2a new merged dictionarymerged = defaults | user
pop(key, default)remove and return a valued.pop("tmp", None)
popitem()remove the last added paird.popitem()
setdefault(key, value)return the value, creating it if the key is missingd.setdefault("tags", []).append("py")
key in dchecks whether a key existsif "name" in d:
dict.fromkeys()a dictionary from keys with one shared valuedict.fromkeys("abc", 0)
len(d), del d[key]size and deletiondel d["old"]

Tuples and sets

OperationExample → result
Tuple unpackingx, y = (3, 4)
Add to a sets.add(5), remove — s.discard(5)
Union / intersection{1, 2} | {2, 3} → {1, 2, 3}; {1, 2} & {2, 3} → {2}
Difference{1, 2} - {2} → {1}
Remove duplicates from a listlist(dict.fromkeys(items)) — keeps the order

Exceptions and files

try:
    number = int(input("Number: "))
except ValueError as err:
    print("This is not a number:", err)
else:
    print("Success")
finally:
    print("Always runs")

with open("data.txt", "w", encoding="utf-8") as f:
    f.write("a line\n")

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())
ExceptionWhen it occurs
SyntaxError, IndentationErroran error in the syntax or the indentation
NameErrora name is not defined (a typo)
TypeErroran operation with an unsuitable type: "1" + 1
ValueErrorthe right type but a wrong value: int("abc")
IndexError, KeyErrorno such index or key
FileNotFoundErrorthe file was not found
ZeroDivisionErrordivision by zero

Classes

from dataclasses import dataclass

class Dog:
    def __init__(self, name: str):
        self.name = name

    def bark(self) -> str:
        return f"{self.name}: Woof!"

@dataclass
class Point:
    x: float
    y: float

print(Dog("Rex").bark())   # Rex: Woof!
print(Point(1, 2))         # Point(x=1, y=2)

Built-in Python modules

The standard library comes with the interpreter — a single import is enough.

ModuleWhat forExample
mathmathematicsmath.sqrt(16) → 4.0
randomrandom numbersrandom.randint(1, 6), random.choice(items)
datetimedates and timesdatetime.date.today()
pathlibpaths and filesPath("data").glob("*.csv")
os, systhe system, environment variables, argumentsos.environ.get("HOME"), sys.argv
jsonreading and writing JSONjson.loads(text), json.dumps(obj, ensure_ascii=False)
csvCSV tablescsv.DictReader(f)
collectionsCounter, defaultdict, dequeCounter("banana").most_common(1) → [('a', 3)]
itertoolscombinations and chains of iteratorsitertools.chain(a, b)
reregular expressionsre.findall(r"\d+", s)
timepauses and timingtime.sleep(1), time.perf_counter()
asyncioasynchronous codeasyncio.run(main())

Python 3.15 added lazy imports (PEP 810): lazy import pandas as pd postpones loading the module until it is first used, so a script with heavy dependencies starts noticeably faster.

Python commands in the terminal

These Python commands launch the interpreter, create virtual environments and install libraries. On Windows, people usually write python or py instead of python3.

CommandWhat it does
python3 --versionshow the version
python3open the interactive REPL console (exit with exit())
python3 script.pyrun a file
python3 -c "print(2 + 2)"run a single line
python3 -m venv .venvcreate a virtual environment
source .venv/bin/activate / .venv\Scripts\activateactivate the environment (Linux, macOS / Windows)
python3 -m pip install requestsinstall a package
pip list, pip freeze > requirements.txtlist packages and save them
pip install -r requirements.txtinstall dependencies from a file
python3 -m http.server 8000a simple web server in the current folder
uv init, uv add requests, uv run main.pya project, a dependency and running through the uv manager

Common beginner mistakes

  • Comparing with = — a condition needs ==; a single = is assignment.
  • A missing colon after if, for or def causes a SyntaxError.
  • Adding a string and a number: "Age: " + 25 is an error; write f"Age: {25}".
  • Changing a list while looping over it — iterate over a copy for x in a[:] or build a new list.
  • input() returns a string — wrap it in int() or float() for arithmetic.

Summary

Python syntax rests on indentation, colons and a small set of constructs: conditions, for and while loops, functions and classes. Add two dozen built-in functions and the methods of strings, lists and dictionaries, and you will cover most everyday tasks. Save this cheat sheet, and once the tables feel familiar, move on to modules and asynchronous code. All of this is walked through in practice in the course "Python 3.15: from beginner to pro".

FAQ

How many spaces should I use for indentation in Python?

According to PEP 8, 4 spaces per level. The main thing is to be consistent within a block and not to mix in tabs.

What is the difference between a list and a tuple?

A list is mutable: you can extend it and sort it in place. A tuple is immutable, so it can be used as a dictionary key and suits fixed sets of values.

How can I see all the methods of an object directly in Python?

Call dir(obj) for a list of names and help(obj) for descriptions; for example, help(str) shows all string methods.

What is the difference between sort() and sorted()?

The list.sort() method sorts the list itself and returns None, while the sorted() function returns a new list and works with any iterable.

Do I need a semicolon at the end of a line?

No. A semicolon is allowed to separate several statements on one line, but in normal code each statement is written on its own line.