Quick answerCore Python in one line each: x = 5 (variable), f"{x}" (f-string), [1, 2] (list), {"k": 1} (dict), if/elif/else, for x in items:, while cond:, def f(a): return a, class C:, try/except and with open(...) as f:. The sections below show each with runnable examples.
Variables, numbers and printing
Run ▸name = "Ada" # str
age = 36 # int
height = 1.65 # float
is_coder = True # bool
print(name, age)
print(f"{name} is {age} years old") # f-string
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10) # 3.5 3 1 1024
age += 1 # same as age = age + 1
print(type(height), int("42"), float("2.5"), str(99))
Strings
| Code | Result |
|---|---|
s = "Python" | a string |
s[0], s[-1] | 'P', 'n' |
s[1:4], s[::-1] | 'yth', 'nohtyP' |
len(s) | 6 |
s.upper(), s.lower(), s.title() | case changes |
"a,b,c".split(",") | ['a', 'b', 'c'] |
"-".join(["a", "b"]) | 'a-b' |
s.replace("P", "J") | 'Jython' |
" hi ".strip() | 'hi' |
"th" in s, s.startswith("Py") | True, True |
f"{3.14159:.2f}", f"{7:03d}" | '3.14', '007' |
Input
Run ▸name = input("Name: ") # always returns a string
age = int(input("Age: ")) # convert to a number
print(f"Hi {name}, next year you'll be {age + 1}")
Lists
Run ▸nums = [3, 1, 4, 1, 5]
nums.append(9) # add to the end
nums.insert(0, 2) # insert at index 0
nums.remove(1) # remove first 1
last = nums.pop() # remove and return last item
print(nums, last) # [2, 3, 4, 1, 5] 9
print(sorted(nums), sum(nums), max(nums), len(nums))
print(nums[1:3], nums[-2:])
squares = [n * n for n in range(5)] # comprehension
evens = [n for n in nums if n % 2 == 0]
print(squares, evens)
Dictionaries, sets and tuples
Run ▸ages = {"ann": 31, "bob": 25}
ages["cy"] = 40 # add / update
print(ages.get("dan", "unknown")) # safe lookup
for name, age in ages.items():
print(name, age)
del ages["bob"]
print(list(ages.keys()), "ann" in ages)
colors = {"red", "green", "red"} # set: unique items
print(colors, len(colors))
point = (3, 4) # tuple: fixed
x, y = point # unpacking
print(x + y)
Conditions
Run ▸score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"
print(grade)
# comparison: == != < <= > >= logic: and or not membership: in
label = "pass" if score >= 50 else "fail" # one-line if
print(label, 0 < score < 100, not False)
Loops
Run ▸for i in range(3): # 0 1 2
print("i =", i)
for i, fruit in enumerate(["apple", "fig"], start=1):
print(i, fruit)
for a, b in zip([1, 2], ["x", "y"]):
print(a, b)
n = 3
while n > 0:
print(n)
n -= 1
for x in range(10):
if x == 2:
continue # skip the rest of this pass
if x == 4:
break # leave the loop
print("x", x)
Functions
Run ▸def area(width, height=1):
"""Return the area of a rectangle."""
return width * height
print(area(3, 4), area(5), area(height=2, width=6))
def total(*numbers, **options):
result = sum(numbers)
return round(result, options.get("digits", 0))
print(total(1.5, 2.25, digits=1))
double = lambda x: x * 2
print(list(map(double, [1, 2, 3])))
Classes
Run ▸class Pet:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}"
class Dog(Pet): # inheritance
def __init__(self, name):
super().__init__(name, "woof")
print(Dog("Rex").speak())
Errors and exceptions
Run ▸try:
value = int("abc")
except ValueError as err:
print("Not a number:", err)
else:
print("no error")
finally:
print("always runs")
| Error | Usual cause |
|---|---|
SyntaxError | missing colon, bracket or quote |
IndentationError | block not indented consistently |
NameError | typo, or variable used before it's assigned |
TypeError | e.g. "5" + 3 — mixing types |
ValueError | e.g. int("abc") |
IndexError / KeyError | list index or dict key doesn't exist |
Files and modules
Run ▸with open("notes.txt", "w") as f: # "w" write, "a" append, "r" read
f.write("line one\nline two\n")
with open("notes.txt") as f:
for line in f:
print(line.strip())
import math, random
from datetime import date
print(math.sqrt(16), math.pi)
print(random.randint(1, 6) in range(1, 7))
print(date(2026, 1, 1).year)
Practise each section with the auto-checked exercises, and keep the syntax checker handy for typos.
Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.
Frequently asked questions
What should a Python cheat sheet include?
Variables and types, strings, input/output, lists, dictionaries, conditions, loops, functions, classes, exceptions and files — the sections on this page.
Can I download this Python cheat sheet as a PDF?
Use your browser's Print → Save as PDF; the page prints cleanly. Or bookmark it — every example stays runnable online.
Which Python version does this cheat sheet cover?
Python 3 (3.8 and newer). Every example is tested on Python 3 before publishing.