Bytebook Compiler

Real Programs

Python Cheat Sheet

Python on one page: syntax, built-in types and their methods, comprehensions, functions, files, exceptions, classes and the standard-library modules you will reach for most.

3 min read4-question quiz

Syntax at a glance

Python
x = 10                              # variables: no declarations
if x > 5: ...                       # if / elif / else, indentation blocks
for i in range(n): ...              # loop over a range or any iterable
while cond: ...                     # break, continue, loop-else
def f(a, b=2, *args, **kwargs):     # functions with defaults and varargs
    return a + b
lambda x: x * 2                     # anonymous function
class Dog(Animal):                  # class with inheritance
    def __init__(self, name):
        super().__init__(name)
try: ... except ValueError as e: ... else: ... finally: ...
with open("f.txt") as f: ...        # auto-closing resources

Built-in types

Type Literal Mutable Ordered Notes
int, float, bool 3, 3.0, True no — int has unlimited size
str "hi" no yes slicing, methods, f-strings
list [1, 2] yes yes dynamic array
tuple (1, 2) no yes fixed records, dict keys
set {1, 2} yes no unique items, O(1) in
dict {"k": 1} yes insertion order key → value, O(1) lookup

Most-used methods

Type Methods
str split, join, strip, replace, find, count, upper, lower, startswith, isdigit
list append, extend, insert, pop, remove, sort, reverse, index, count, copy
dict get, items, keys, values, pop, setdefault, update
set add, discard, remove, union (|), intersection (&), difference (-)

Built-in functions

len, range, enumerate, zip, sorted, reversed, sum, min, max, abs, round, map, filter, any, all, isinstance, type, input, print, int, float, str, list, dict, set, tuple, open, ord, chr

Comprehensions

Python
[x * x for x in xs if x > 0]          # list
{x % 3 for x in xs}                   # set
{k: v for k, v in pairs}              # dict
sum(x for x in xs)                    # generator expression

Slicing

Expression Meaning
s[a:b] from a up to (not including) b
s[:n] / s[-n:] first n / last n items
s[::-1] reversed copy
s[::2] every second item

Python vs C quick map

C Python
printf("%d\n", x); print(x)
scanf("%d", &x); x = int(input())
for (i = 0; i < n; i++) for i in range(n):
a && b, a || b, !a a and b, a or b, not a
x++ x += 1
NULL None
struct class / @dataclass
malloc / free automatic memory management

Programs to practise

  1. Number programs: prime, factorial, Fibonacci, palindrome, Armstrong, GCD/LCM.
  2. String programs: reverse words, palindrome sentence, vowel count, anagram check, character frequency.
  3. List programs: second largest, remove duplicates keeping order, rotate, merge sorted lists.
  4. Dictionary programs: word frequency, group by first letter, invert a dict, student grade book.
  5. Recursion: power, sum of digits, flatten nested lists, permutations.
  6. Files: count lines/words/characters, CSV average, JSON save/load.
  7. OOP: BankAccount with validation, Shape hierarchy, Vector with dunder methods.
  8. Generators: Fibonacci generator, reading a large file lazily.

Final check: mixed revision

4 questions · pick an answer to check it instantly

  1. 1

    What is [1, 2, 3, 4, 5][-2:]?

  2. 2

    Which is mutable?

  3. 3

    What does {x: x ** 2 for x in range(3)} produce?

  4. 4

    Which statement creates an object of class Car with __init__(self, model)?