Python

Python Cheatsheet

Python is a versatile, readable programming language. This cheatsheet covers the syntax and built-ins you reach for every day.

Python is a high-level, readable programming language used for web development, data science, scripting, and automation. This cheatsheet covers the everyday syntax and built-ins.

Variables & Types

Dynamic typing with common built-in types.

name = "Ada"           # str
age = 36                # int
pi = 3.14               # float
is_dev = True           # bool
nums = [1, 2, 3]        # list
point = (1, 2)          # tuple
user = {"id": 1}        # dict
unique = {1, 2, 3}      # set

Strings

Formatting and common operations.

s = "hello"
f"{s} world"            # f-string -> 'hello world'
s.upper()               # 'HELLO'
s.replace("l", "L")     # 'heLLo'
",".join(["a", "b"])    # 'a,b'
"a,b".split(",")        # ['a', 'b']
len(s)                   # 5

Control Flow

Conditionals and loops.

if age > 18:
    print("adult")
elif age > 12:
    print("teen")
else:
    print("child")

for n in nums:
    print(n)

while age < 40:
    age += 1

Functions

Define, default args, and *args/**kwargs.

def greet(name, greeting="Hi"):
    return f"{greeting}, {name}"

def total(*args, **kwargs):
    return sum(args)

square = lambda x: x * x

List Comprehensions

Concise ways to build collections.

squares = [x*x for x in range(5)]
evens = [x for x in nums if x % 2 == 0]
pairs = {k: v for k, v in user.items()}

Dictionaries

Access and iterate key-value data.

user["name"] = "Ada"    # set
user.get("id", 0)       # safe access
for k, v in user.items():
    print(k, v)
"id" in user             # membership

Error Handling

Catch and raise exceptions.

try:
    risky()
except ValueError as e:
    print(e)
finally:
    cleanup()

raise ValueError("bad input")

Classes

Object-oriented basics.

class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        return f"{self.name} says woof"

d = Dog("Rex")
d.bark()

Files

Read and write with context managers.

with open("file.txt") as f:
    data = f.read()

with open("out.txt", "w") as f:
    f.write("hello")

Python's readability makes it beginner-friendly and powerful. Master these basics, then explore the standard library and packages like requests, pandas, and FastAPI.

For full documentation, see https://docs.python.org/3/

Promote your content

Reach over 400,000 developers and grow your brand.

Join our developer community

Hang out with over 4,500 developers and share your knowledge.