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

URL: https://skillaria.top/en/guides/python/python-cheat-sheet

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`.

| Construct | Example | Explanation |
| --- | --- | --- |

| Comment | `# text` | everything from # to the end of the line is ignored |

| Variable | `age = 25` | no type is declared, the value determines it |

| Multiple assignment | `a, b = 1, 2` | unpacking; swapping values: `a, b = b, a` |

| Output | `print("Hello", name)` | arguments are separated by a space |

| Input | `s = input("Name: ")` | always returns a string |

| f-string | `f"{name}: {price:.2f}"` | inserts expressions and applies formatting |

| Type annotation | `count: int = 0` | a hint for IDEs and checkers, not checked at run time |

| Empty block | `pass` | a placeholder where the syntax requires a body |

| Import | `from math import sqrt` | connects a module or a name from it |

### Data types

| Type | Literal | Mutable |
| --- | --- | --- |

| `int` | `42`, `1_000_000` | no |

| `float` | `3.14`, `1e-3` | no |

| `bool` | `True`, `False` | no |

| `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 |

| `NoneType` | `None` | — |

### Operators

| Group | Operators | Example → result |
| --- | --- | --- |

| Arithmetic | `+ - * / // % **` | `7 // 2` → 3, `7 % 2` → 1, `2 ** 10` → 1024 |

| Comparison | `== != < > <= >=` | `1 < x < 10` — a chained comparison |

| Logical | `and or not` | `x or "default"` |

| Membership | `in`, `not in` | `"a" in "abc"` → True |

| Identity | `is`, `is not` | `x 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
```

| Command | What it does |
| --- | --- |

| `break` | leaves the loop early |

| `continue` | moves on to the next iteration |

| `else` on a loop | runs 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!
```

| Element | Meaning |
| --- | --- |

| `def f(a, b=1)` | a parameter with a default value |

| `*args` | any number of positional arguments (a tuple) |

| `**kwargs` | any number of named arguments (a dictionary) |

| `return` | returns a value; without it the function returns `None` |

| `lambda x: ...` | a short anonymous function with a single expression |

| `global`, `nonlocal` | change 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.

| Function | What it does | Example → result |
| --- | --- | --- |

| `print()` | prints values | `print(1, 2, sep="-")` → 1-2 |

| `input()` | reads a line from the keyboard | `int(input())` |

| `len()` | length of a collection or string | `len("abc")` → 3 |

| `type()` | the type of an object | `type(3.0)` → <class 'float'> |

| `isinstance()` | checks the type | `isinstance(5, int)` → True |

| `int() float() str() bool()` | type conversion | `int("42")` → 42 |

| `list() tuple() set() dict()` | create collections | `list("ab")` → ['a', 'b'] |

| `range()` | a range of numbers | `list(range(3))` → [0, 1, 2] |

| `enumerate()` | pairs of (index, element) | `list(enumerate("ab"))` → [(0, 'a'), (1, 'b')] |

| `zip()` | pairs up sequences element by element | `list(zip([1, 2], "ab"))` → [(1, 'a'), (2, 'b')] |

| `sum() min() max()` | sum, minimum, maximum | `max([3, 7, 1])` → 7 |

| `abs() round()` | absolute value and rounding | `round(3.14159, 2)` → 3.14 |

| `sorted()` | a new sorted list | `sorted(words, key=len, reverse=True)` |

| `reversed()` | an iterator in reverse order | `list(reversed([1, 2]))` → [2, 1] |

| `map() filter()` | apply a function / filter | `list(map(str, [1, 2]))` → ['1', '2'] |

| `any() all()` | at least one / all are true | `all(x > 0 for x in nums)` |

| `open()` | opens a file | `open("a.txt", encoding="utf-8")` |

| `help() dir()` | help and a list of attributes | `help(str.split)`, `dir(list)` |

| `id() hash()` | identity and hash of an object | `hash("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.

| Method | Example → 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.

| Operation | What it does | Example |
| --- | --- | --- |

| `append(x)` | adds to the end | `a.append(4)` |

| `extend(iter)` | adds all elements | `a.extend([5, 6])` |

| `insert(i, x)` | inserts at an index | `a.insert(0, "first")` |

| `remove(x)` | removes the first occurrence of a value | `a.remove(3)` |

| `pop(i)` | removes and returns an element (the last one by default) | `last = a.pop()` |

| `clear()` | empties the list | `a.clear()` |

| `index(x)` | index of the first occurrence | `a.index("b")` |

| `count(x)` | number of occurrences | `a.count(1)` |

| `sort()` | sorts in place | `a.sort(key=str.lower)` |

| `reverse()` | reverses in place | `a.reverse()` |

| `copy()` | shallow copy | `b = a.copy()` |

| `del a[i]` | deletes by index or slice | `del a[1:3]` |

| Slices | `a[start:stop:step]` | `a[-1]` — the last one, `a[:3]` — the first three |

## Python dictionary methods

| Operation | What it does | Example |
| --- | --- | --- |

| `d[key]` | value by key, missing key — `KeyError` | `d["name"]` |

| `get(key, default)` | the value, or a fallback | `d.get("age", 0)` |

| `d[key] = value` | add or change | `d["city"] = "Boston"` |

| `keys() values() items()` | keys, values, pairs | `for k, v in d.items():` |

| `update()` | merge with another dictionary | `d.update({"a": 1})` |

| `d1 | d2` | a new merged dictionary | `merged = defaults | user` |

| `pop(key, default)` | remove and return a value | `d.pop("tmp", None)` |

| `popitem()` | remove the last added pair | `d.popitem()` |

| `setdefault(key, value)` | return the value, creating it if the key is missing | `d.setdefault("tags", []).append("py")` |

| `key in d` | checks whether a key exists | `if "name" in d:` |

| `dict.fromkeys()` | a dictionary from keys with one shared value | `dict.fromkeys("abc", 0)` |

| `len(d)`, `del d[key]` | size and deletion | `del d["old"]` |

### Tuples and sets

| Operation | Example → result |
| --- | --- |

| Tuple unpacking | `x, y = (3, 4)` |

| Add to a set | `s.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 list | `list(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())
```

| Exception | When it occurs |
| --- | --- |

| `SyntaxError`, `IndentationError` | an error in the syntax or the indentation |

| `NameError` | a name is not defined (a typo) |

| `TypeError` | an operation with an unsuitable type: `"1" + 1` |

| `ValueError` | the right type but a wrong value: `int("abc")` |

| `IndexError`, `KeyError` | no such index or key |

| `FileNotFoundError` | the file was not found |

| `ZeroDivisionError` | division 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.

| Module | What for | Example |
| --- | --- | --- |

| `math` | mathematics | `math.sqrt(16)` → 4.0 |

| `random` | random numbers | `random.randint(1, 6)`, `random.choice(items)` |

| `datetime` | dates and times | `datetime.date.today()` |

| `pathlib` | paths and files | `Path("data").glob("*.csv")` |

| `os`, `sys` | the system, environment variables, arguments | `os.environ.get("HOME")`, `sys.argv` |

| `json` | reading and writing JSON | `json.loads(text)`, `json.dumps(obj, ensure_ascii=False)` |

| `csv` | CSV tables | `csv.DictReader(f)` |

| `collections` | Counter, defaultdict, deque | `Counter("banana").most_common(1)` → [('a', 3)] |

| `itertools` | combinations and chains of iterators | `itertools.chain(a, b)` |

| `re` | regular expressions | `re.findall(r"\d+", s)` |

| `time` | pauses and timing | `time.sleep(1)`, `time.perf_counter()` |

| `asyncio` | asynchronous code | `asyncio.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`.

| Command | What it does |
| --- | --- |

| `python3 --version` | show the version |

| `python3` | open the interactive REPL console (exit with `exit()`) |

| `python3 script.py` | run a file |

| `python3 -c "print(2 + 2)"` | run a single line |

| `python3 -m venv .venv` | create a virtual environment |

| `source .venv/bin/activate` / `.venv\Scripts\activate` | activate the environment (Linux, macOS / Windows) |

| `python3 -m pip install requests` | install a package |

| `pip list`, `pip freeze > requirements.txt` | list packages and save them |

| `pip install -r requirements.txt` | install dependencies from a file |

| `python3 -m http.server 8000` | a simple web server in the current folder |

| `uv init`, `uv add requests`, `uv run main.py` | a 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.


---
Source: Skillaria.Top (https://skillaria.top)
