JcHub
Cheat sheetFree, no sign-upPDF

Python 3 Cheat Sheet: Essential Syntax and Functions

A quick reference guide covering essential Python 3 syntax, data structures, and common built-in functions.

Updated on November 9, 2026

Variables & Data Types

  • balance = 15000.50Declares a floating-point number for monetary amounts. Beware of float rounding inaccuracies in precision operations.
  • city = "Nairobi"Creates an immutable string object. Be careful not to mix single and double quotes inconsistently.
  • is_active = TrueAssigns a boolean logic value. Note that True and False must be capitalized in Python.
  • value = NoneRepresents the absence of a value or null state. Test with is None rather than equality comparison.

Control Flow

  • if x > 10: print("OK")Executes code conditionally. Python strictly requires consistent 4-space indentation.
  • for item in items: print(item)Iterates over items in a sequence. Avoid mutating the list while looping through it.
  • while count > 0: count -= 1Loops while a condition remains true. Ensure the condition eventually terminates to avoid infinite loops.
  • match status: case 200: print("OK")Pattern matching syntax added in Python 3.10. Throws a SyntaxError on older Python versions.

Lists & Dictionaries

  • cities = ["Lagos", "Accra"]Creates an ordered, mutable sequence of items. Access items using zero-based indexing.
  • cities.append("Kigali")Appends an item to the end of the list in place and returns None.
  • user = {"name": "Awa", "age": 28}Stores key-value pairs. Dictionary keys must be immutable types like strings or numbers.
  • age = user.get("age", 0)Retrieves a key value safely without raising KeyError if the key is missing from the dict.

Functions & Modules

  • def calculate(a, b=10): return a * bDefines a function with default parameter values. Never use mutable objects like lists as defaults.
  • square = lambda x: x ** 2Creates a small anonymous inline function. Best reserved for simple one-line callback functions.
  • import mathImports an entire built-in module. Call contained functions using module dot syntax like math.sqrt().
  • from datetime import datetimeImports a specific object from a module directly into the current namespace.

Error Handling & Files

  • try: res = 10 / 0 except ZeroDivisionError: res = 0Catches and handles runtime exceptions gracefully. Avoid bare except clauses without specific errors.
  • with open("file.txt", "r") as f: content = f.read()Opens a file safely using context manager syntax, ensuring automatic cleanup when finished.
  • raise ValueError("Invalid value")Manually raises an explicit exception when invalid arguments or error conditions occur.
  • finally: print("Cleanup")Specifies a block that runs regardless of whether an exception occurred inside the try block.

Strings & Utilities

  • text = f"Total: {amount} USD"Formats string using f-string interpolation (Python 3.6+). Highly readable and efficient.
  • [x**2 for x in range(5)]Creates a list compactly using list comprehension. Keep expressions simple for readability.
  • len(collection)Returns the total number of items in a sequence or collection like strings, lists, or dicts.
  • list(enumerate(cities))Pairs each item in an iterable with its corresponding numeric index starting at 0.

Other resources

Need help with your website?

I build your custom website.

Showcase site, online shop, management tool: let’s talk about your project.

See the services