Python · Fundamentals · Quick Reference
Python
Cheatsheet
A quick reference guide for Python fundamentals, syntax, and common operations — from basics and data types through to file handling, exceptions, and useful one-liners.
🐍 1. Basics
Variables, printing, input, and comments.
# Variables — no type declaration needed name = "Kenneth" age = 25 score = 98.5 active = True # Print print("Hello, World!") print(f"Name: {name}, Age: {age}") # f-string # Input user = input("Enter your name: ") # Multiple assignment x, y, z = 1, 2, 3 # Check type type(name) # <class 'str'>
📦 2. Data Types
Python's core built-in types: strings, lists, tuples, sets, and dicts.
Strings
s = "hello world" s.upper() # HELLO WORLD s.title() # Hello World s.split(" ") # ['hello','world'] s.replace("hello","hi") s[0:5] # hello (slice) len(s) # 11 ",".join(["a","b"]) # "a,b"
Lists
lst = [1, 2, 3, 4] lst.append(5) # add to end lst.insert(0, 0) # insert at index lst.remove(3) # remove value lst.pop() # remove last lst.sort() # sort in-place lst[1:3] # [2, 3] lst[::-1] # reversed
Dictionaries
d = {"name": "Ken", "age": 25}
d["age"] # 25
d.get("city", "N/A") # safe get
d["city"] = "London"
d.keys()
d.values()
d.items() # key-value pairs
"name" in d # True
Tuples & Sets
# Tuple — immutable t = (1, 2, 3) t[0] # 1 a, b, c = t # unpack # Set — unique values s = {1, 2, 2, 3} # {1, 2, 3} s.add(4) s.discard(1) s1 & s2 # intersection s1 | s2 # union
🔀 3. Control Flow
if / elif / else
if age >= 18: print("Adult") elif age >= 13: print("Teen") else: print("Child") # Ternary label = "Adult" if age >= 18 else "Minor"
Loops
# for loop for i in range(5): print(i) for item in ["a", "b", "c"]: print(item) # while loop n = 0 while n < 5: n += 1 # enumerate for i, v in enumerate(lst): print(i, v)
⚙️ 4. Functions
# Basic function def greet(name, greeting="Hello"): return f"{greeting}, {name}!" greet("Ken") # Hello, Ken! greet("Ken", "Hi") # Hi, Ken! # *args and **kwargs def add_all(*args): return sum(args) def show_info(**kwargs): for k, v in kwargs.items(): print(f"{k}: {v}") # Lambda (anonymous function) square = lambda x: x ** 2 square(4) # 16 # Type hints (Python 3.5+) def add(a: int, b: int) -> int: return a + b
⚡ 5. List Comprehensions
Compact syntax for building lists, dicts, and sets in a single line.
# List comprehension squares = [x**2 for x in range(10)] # With condition evens = [x for x in range(20) if x % 2 == 0] # Nested comprehension matrix = [[i*j for j in range(3)] for i in range(3)] # Dict comprehension word_len = {w: len(w) for w in ["apple", "cat", "dog"]} # Set comprehension unique_lens = {len(w) for w in ["hi", "hey", "hello"]} # Generator expression (memory-efficient) total = sum(x**2 for x in range(1000))
📁 6. Working with Files
# Read entire file with open("file.txt", "r") as f: content = f.read() # Read line by line with open("file.txt") as f: for line in f: print(line.strip()) # Read all lines into a list lines = f.readlines() # Write to file with open("output.txt", "w") as f: f.write("Hello\n") # Append to file with open("output.txt", "a") as f: f.write("New line\n") # File modes: "r" read "w" write "a" append "rb" read binary
🛡️ 7. Exception Handling
# try / except / else / finally try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (TypeError, ValueError): print("Type or value error") else: print("No error occurred") finally: print("Always runs") # Raise custom exception raise ValueError("Invalid input") # Custom exception class class AppError(Exception): pass raise AppError("Something went wrong")
📚 8. Modules & Imports
# Standard imports import os import sys import math import datetime import json import re # Aliased import import numpy as np import pandas as pd # Selective import from math import sqrt, pi from os.path import join, exists # Useful os / sys snippets os.getcwd() # current directory os.listdir(".") # list files os.path.join("a", "b") # path join sys.argv # command-line args
🔧 9. Common Built-in Functions
| Function | Description |
|---|---|
| len(x) | Length of a sequence or collection |
| range(start, stop, step) | Generate a range of integers |
| enumerate(iterable) | Returns (index, value) pairs |
| zip(a, b) | Pair elements from two iterables |
| map(func, iterable) | Apply function to each element |
| filter(func, iterable) | Keep elements where function returns True |
| sorted(iterable, key, reverse) | Return a new sorted list |
| min(x) / max(x) | Minimum or maximum value |
| sum(iterable) | Sum all numeric elements |
| any(iterable) / all(iterable) | True if any/all elements are truthy |
| isinstance(obj, type) | Check object type |
| int() / str() / float() / list() | Type conversion |
✨ 10. Useful One-Liners
# Swap variables a, b = b, a # Flatten a nested list flat = [x for sub in nested for x in sub] # Count items in a list from collections import Counter counts = Counter(["a", "b", "a", "c", "a"]) # Reverse a string rev = s[::-1] # Remove duplicates preserving order unique = list(dict.fromkeys(lst)) # Check palindrome is_pal = s == s[::-1] # Merge two dicts (Python 3.9+) merged = dict1 | dict2 # Unpack and ignore first, *rest = [1, 2, 3, 4] # Sort dict by value sorted(d.items(), key=lambda x: x[1]) # Read CSV in one line rows = [line.split(",") for line in open("f.csv")]
📚 Further Learning
Official Python Documentation
docs.python.org — language reference, library, and tutorials
The Python Tutorial
docs.python.org/3/tutorial — official beginner guide by the PSF
Python Software Foundation
python.org/psf — the non-profit behind Python
Python Standard Library Reference
docs.python.org — full index of built-in modules