




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





x = 10 # int pi = 3.14 # float name = "Ada" # str ok = True # bool nothing = None # NoneType
print(f"{name} is {x} years old") # f-string print(f"{pi:.2f}") # 3. type(x); isinstance(x, int)
a, b = 1, 2 # multiple assignment a, b = b, a # swap
Strings
s = "Hello, World" s.lower(); s.upper(); s.title() s.strip(); s.lstrip(); s.rstrip() s.split(",") # ['Hello', ' World'] ", ".join(["a", "b"]) # 'a, b' s.replace("World", "Python") s.startswith("He"); s.endswith("ld") s.find("o") # index or - s[0]; s[-1]; s[0:5]; s[::-1] # indexing, slicing, reverse
Lists
nums = [3, 1, 2] nums.append(4) # add to end nums.insert(0, 9) # insert at index nums.extend([5, 6]) nums.remove(1) # remove first matching value last = nums.pop() # remove and return last nums.sort(reverse=True) # in place sorted(nums) # returns new list len(nums); sum(nums); max(nums); min(nums) nums[1:3]; nums[::2]
Tuples & Sets
t = (1, 2, 3) # immutable x, y, z = t # unpacking
s = {1, 2, 3} # unique, unordered s.add(4); s.discard(2) a | b; a & b; a - b; a ^ b # union, intersection, difference, symmetric diff
Match Statement (3.10+)
match command: case "start": ... case ["go", direction]: ... case {"type": "click", "x": x}: ... case _: ...
Functions
def greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}!"
def total(*args, **kwargs): # variable positional / keyword args return sum(args)
square = lambda x: x * x
def f(a, /, b, *, c): # a positional-only, c keyword-only ...
Comprehensions
squares = [x2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] lookup = {name: len(name) for name in names} unique = {x % 3 for x in range(10)} gen = (x2 for x in range(10)) # lazy generator
Useful Built-ins
map(str, [1, 2, 3]); filter(None, items) any(x > 5 for x in nums); all(x > 0 for x in nums) sorted(items, key=lambda i: i["age"], reverse=True) reversed(items); abs(-3); round(3.14159, 2); divmod(7, 2) min(items, key=len)
Classes & Dataclasses
class Animal: def init(self, name): self.name = name
def speak(self): return f"{self.name} makes a sound"
def repr(self): return f"Animal({self.name!r})"
class Dog(Animal): def speak(self): return f"{self.name} barks"
from dataclasses import dataclass
@dataclass class Point: x: float y: float = 0.
Modules & Standard Library
import os, sys, math, random from datetime import datetime, timedelta from collections import Counter, defaultdict, deque from itertools import chain, groupby, combinations from functools import lru_cache, reduce
Counter("banana").most_common(2) now = datetime.now().strftime("%Y-%m-%d %H:%M")
Decorators & Generators
import functools
def timer(func): @functools.wraps(func) def wrapper(*args, *kwargs): import time start = time.perf_counter() result = func(args, **kwargs) print(f"{func.name}: {time.perf_counter() - start:.3f}s") return result return wrapper
@timer def work(): ...
def countdown(n): # generator while n > 0: yield n n -= 1
Async Basics
import asyncio
async def fetch(n): await asyncio.sleep(1) return n
async def main(): results = await asyncio.gather(fetch(1), fetch(2), fetch(3)) print(results)
asyncio.run(main())
Virtual Environments & pip
python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install requests pandas pip freeze > requirements.txt pip install -r requirements.txt deactivate
Common Pitfalls