Neonová encyklopedie: od základů po pokročilé témata, se spoustou ukázek a strukturovanými přehledy.
Ilustrační neon — nahraď vlastní grafikou (SVG grid, glitch efekty).
# komentář
x = 42 # int
pi = 3.1415 # float
name = "Python" # str
is_ready = True # bool
items = [1, 2, 3] # list
user = {"name": "Neo", "lvl": 7} # dict
if x > 10:
print("víc než 10")
elif x == 10:
print("deset")
else:
print("méně")
for i in range(5):
print(i)
while True:
break
def greet(name: str) -> str:
return f"Ahoj, {name}!"
add = lambda a, b: a + b
def power(x, *, exp=2):
return x ** exp
squares = [n*n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
pairs = [(a, b) for a in range(3) for b in range(3)]
arr = [3,1,4]
arr.append(1); arr.sort()
s = {1,2,2,3}
d = {"a": 1}; d.update({"b": 2})
t = (1,2,3); a,b,c = t
def f(a, b=0, *args, **kwargs):
print(a, b, args, kwargs)
import math
from pathlib import Path
from pkg import util as u
project/
pkg/
__init__.py
core.py
utils/
__init__.py
io.py
class Player:
def __init__(self, name: str, hp: int = 100):
self.name = name
self.hp = hp
def hit(self, dmg: int):
self.hp = max(0, self.hp - dmg)
class Mage(Player):
def cast(self):
return "⚡️"
class LoggerMixin:
def log(self, msg): print(msg)
class BattleMage(Mage, LoggerMixin):
pass
class Vec2:
def __init__(self, x, y): self.x, self.y = x, y
def __repr__(self): return f"Vec2({self.x},{self.y})"
def __add__(self, o): return Vec2(self.x + o.x, self.y + o.y)
try:
risky()
except ValueError as e:
print("Chyba:", e)
finally:
cleanup()
with open("data.txt") as f:
for line in f:
print(line.strip())
| Modul | Kategorie | Stručné použití | Příklady |
|---|---|---|---|
| pathlib | IO | Práce s cestami | Path("dir").glob("*.py") |
| os | OS | Procesy, prostředí | os.getenv("HOME") |
| sys | OS | Interakce s interpretem | sys.argv, sys.path |
| json | Data | Serializace JSON | json.dumps(obj) |
| re | Text | Regulární výrazy | re.findall(r"\\w+", s) |
| logging | Debug | Logování | logging.info("msg") |
| datetime | Čas | Datum/čas | datetime.now() |
| time | Čas | Časové funkce | time.sleep(1) |
| functools | Text | Decoratory, partial | @lru_cache |
| itertools | Data | Kombinatorika | chain, product |
| collections | Data | deque, Counter | Counter(words) |
| csv | IO | CSV čtení/zápis | csv.DictReader(f) |
| subprocess | OS | Spouštění procesů | run(["ls"]) |
| argparse | OS | CLI parsování | ArgumentParser() |
| socket | Síť | TCP/UDP sokety | socket.socket() |
import threading
def work():
print("vlákno")
t = threading.Thread(target=work)
t.start(); t.join()
from multiprocessing import Process, Queue
def worker(q):
q.put("ready")
q = Queue()
p = Process(target=worker, args=(q,))
p.start(); print(q.get()); p.join()
import asyncio
async def fetch(i):
await asyncio.sleep(0.1)
return f"ok {i}"
async def main():
results = await asyncio.gather(*(fetch(i) for i in range(5)))
print(results)
asyncio.run(main())
from typing import List, Dict, Optional, Protocol
class SupportsLen(Protocol):
def __len__(self) -> int: ...
def total(xs: List[int]) -> int:
return sum(xs)
from dataclasses import dataclass
@dataclass
class Config:
host: str = "localhost"
port: int = 8000
from pathlib import Path
p = Path("data") / "file.txt"
p.write_text("hello")
print(p.read_text())
import csv, json
with open("data.csv") as f:
rows = list(csv.DictReader(f))
data = {"users": rows}
print(json.dumps(data, indent=2))
import socket
s = socket.socket()
s.bind(("localhost", 9000))
s.listen()
import requests
r = requests.get("https://example.com")
print(r.status_code, r.text[:80])
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"msg": "world"}
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
def test_len():
assert len([1,2,3]) == 3
# vytvoření venv
python -m venv .venv
source .venv/bin/activate # Windows: .venv\\Scripts\\activate
pip install requests
poetry init
poetry add fastapi
poetry run python app.py
python -m build # vytvoří sdist a wheel
pip install dist/pkg-0.1.0-py3-none-any.whl
import numpy as np
a = np.arange(9).reshape(3,3)
print(a.mean(), a.sum())
import pandas as pd
df = pd.DataFrame({"x":[1,2,3],"y":[9,8,7]})
print(df.describe())
import matplotlib.pyplot as plt
plt.plot([1,2,3],[3,1,4]); plt.show()
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def index():
return {"ok": True}
# django-admin startproject mysite
# python manage.py runserver
import hashlib, secrets
salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", b"pwd", salt, 100_000)
user = "Neo"
print(f"{user=}") # user='Neo'
print(f"{10/3:.2f}") # 3.33
[n*n for n in range(10) if n%2==0]
def log(fn):
def wrap(*a, **k):
print("call", fn.__name__)
return fn(*a, **k)
return wrap