appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Python cheat sheet

Free and printable

Core Python 3 syntax for quick lookup.

Basics

x = 5
Assign a value (no declaration needed)
print(f"Total: {x * 2}")
Print with an f-string
7 // 2 7 % 2 2 ** 3
Floor division, remainder, power
int("42") float("3.5") str(7)
Convert types
type(x)
Show the type of a value
input("Name: ")
Read text from the user

Strings

s.upper() s.lower()
Change case
s.strip()
Remove spaces at both ends
s.split(",")
Split into a list
",".join(items)
Join a list into a string
s.replace("a", "b")
Replace text
s[0] s[-1] s[1:4]
First, last, slice

Lists

items = [1, 2, 3]
Create a list
items.append(4)
Add to the end
items.pop()
Remove and return the last item
len(items)
Number of items
sorted(items, reverse=True)
New sorted list, descending
[n * 2 for n in items if n > 1]
List comprehension

Dictionaries

d = {"a": 1}
Create a dictionary
d["b"] = 2
Add or change a key
d.get("c", 0)
Read with a default
for k, v in d.items():
Loop over keys and values
"a" in d
Check a key

Control flow

if x > 0: elif x == 0: else:
Decisions (indent the block)
for i in range(3):
Loop 0, 1, 2
while cond:
Loop while true
break continue
Leave the loop, skip a round
def f(a, b=1): return a + b
Define a function

Files and errors

with open("f.txt", encoding="utf-8") as f:
Open a file safely
f.read() f.readlines()
Whole text, list of lines
open("f.txt", "w")
Write mode (erases the file first)
try: ... except ValueError: ...
Handle a specific error
python3 -m venv .venv
Create a virtual environment
pip install <package>
Install a package

More cheat sheets