Corso Python
Cheatsheet
Un riferimento veloce — la sintassi essenziale di Python moderno su una pagina sola. Usa Ctrl/Cmd + P per stamparla.
Python · Cheatsheet — eLearner.app
Variabili e tipi
Assegnazione
x = 10 # int pi = 3.14 # float nome = "Anna" # str attivo = True # bool vuoto = NoneNiente let/const/var: Python non ha dichiarazione, solo assegnazione.
Tipi e conversioni
type(42) # <class 'int'> int("42") # 42 str(3.14) # '3.14' float("1.5") # 1.5 bool(0) # FalseConfronti
1 == 1.0 # True 1 is 1.0 # False (identità vs uguaglianza) None is None # True (sempre is con None) "a" in "casa" # TrueUsa == per uguaglianza, is solo con None/True/False.
Stringhe
f-string
nome = "Mondo" msg = f"Ciao, {nome}!" # Espressioni e formattazione: f"pi = {3.14159:.2f}" # 'pi = 3.14' f"{42:>5}" # ' 42'Metodi comuni
len("ciao") # 4 "ciao".upper() # 'CIAO' " ciao ".strip() # 'ciao' "a,b,c".split(",") # ['a','b','c'] "-".join(["a","b","c"]) # 'a-b-c' "hello".startswith("he") # True "hello".replace("l", "L")Slicing
s = "Python" s[0] # 'P' s[-1] # 'n' s[1:4] # 'yth' s[:3] # 'Pyt' s[::-1] # 'nohtyP'
Numeri e math
Operatori
7 // 2 # 3 (divisione intera) 7 % 2 # 1 (resto) 2 ** 10 # 1024 (potenza) abs(-5) # 5 round(1.6) # 2Modulo math
import math math.pi # 3.141592653589793 math.sqrt(16) # 4.0 math.floor(1.9) # 1 math.ceil(1.1) # 2 math.log(math.e) # 1.0
Liste
Creare e accedere
a = [1, 2, 3] a[0] # 1 len(a) # 3 a.append(4) # [1,2,3,4] a.pop() # rimuove l'ultimo a[1:3] = [9] # slicing in scritturaComprehensions
[x * 2 for x in range(5)] # [0,2,4,6,8] [x for x in nums if x > 0] # filtro [(x, y) for x in xs for y in ys] # prodotto cartesianoOrdinare
sorted([3, 1, 2]) # [1,2,3] (copia) [3,1,2].sort() # in-place sorted(utenti, key=lambda u: u["eta"])
Dizionari
Creare e accedere
u = {"nome": "Anna", "eta": 30} u["nome"] # 'Anna' u.get("email", "?") # default u["email"] = "x@y" del u["eta"]Iterare
for k in u: ... for k, v in u.items(): ... list(u.keys()) list(u.values())Comprehensions
{x: x*x for x in range(4)} # {0:0,1:1,2:4,3:9} {k: v for k, v in u.items() if v} # filtro
Tuple e set
Tuple (immutabili)
t = (1, 2, 3) x, y, z = t # unpacking t + (4, 5) # (1,2,3,4,5) len(t)Set (insieme di valori unici)
s = {1, 2, 3} s.add(4) s & {2, 3, 5} # intersezione: {2,3} s | {5} # unione set("abracadabra") # {'a','b','r','c','d'}
Controllo del flusso
if / elif / else
if x > 0: print("positivo") elif x == 0: print("zero") else: print("negativo") # Ternario etichetta = "ok" if x > 0 else "ko"for / while
for i in range(5): print(i) for item in lista: ... for i, item in enumerate(lista): ... while cond: ...break / continue
for n in nums: if n < 0: continue # salta if n > 100: break # esci ...try / except
try: valore = int(s) except ValueError as err: print("non e' un numero:", err) else: print("ok:", valore) finally: print("sempre")
Funzioni
Definire
def somma(a, b): return a + b # Tipi opzionali (type hints) def saluta(nome: str = "Mondo") -> str: return f"Ciao, {nome}"Args variabili
def somma(*numeri): return sum(numeri) somma(1, 2, 3) # 6 somma(*[1, 2, 3]) # 6 def config(**opts): print(opts) config(host="localhost", port=8000)lambda
quadrato = lambda x: x * x quadrato(5) # 25 sorted(items, key=lambda i: i.prezzo)Lambda = funzione anonima a una sola espressione. Per cose più lunghe usa def.
Classi
Classe base
class Punto: def __init__(self, x, y): self.x = x self.y = y def distanza_origine(self): return (self.x ** 2 + self.y ** 2) ** 0.5 p = Punto(3, 4) p.distanza_origine() # 5.0Ereditarietà
class Animale: def __init__(self, nome): self.nome = nome def verso(self): return "..." class Cane(Animale): def verso(self): return "bau" Cane("Fido").verso() # 'bau'Dunder methods
class Soldi: def __init__(self, n): self.n = n def __repr__(self): return f"Soldi({self.n})" def __add__(self, other): return Soldi(self.n + other.n)
Moduli e import
Import
import math from math import sqrt, pi from math import sqrt as radq import os.path as pLibreria standard utili
import json, datetime, pathlib, re, collections, itertools, csv json.dumps({"a": 1}) datetime.date.today() pathlib.Path("file.txt").read_text() re.findall(r"\d+", "ho 3 mele e 12 pere") collections.Counter("abracadabra")
Python moderno
Type hints
def somma(nums: list[int]) -> int: return sum(nums) def cerca(id: int) -> str | None: ... from typing import Callable f: Callable[[int], int] = lambda x: x + 1Solo annotazioni: Python NON le verifica a runtime. Usa mypy per il check statico.
dataclass
from dataclasses import dataclass, field @dataclass class Punto: x: float y: float @dataclass(frozen=True) class Coord: lat: float lon: float @dataclass class Cestino: items: list = field(default_factory=list)Mai default = []: usa field(default_factory=list).
Context manager
with open("f.txt") as f: dati = f.read() from contextlib import contextmanager, suppress @contextmanager def timer(): import time; t0 = time.perf_counter() try: yield finally: print(time.perf_counter() - t0) with suppress(FileNotFoundError): open("forse.txt").read()Decoratori
from functools import wraps, lru_cache def log(func): @wraps(func) def wrapper(*a, **kw): print(func.__name__) return func(*a, **kw) return wrapper @lru_cache(maxsize=None) def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)