1
// TEMEL SEVİYE · BEGINNER
Kurulum · Syntax · Veri Yapıları · Fonksiyonlar
1.1 Ortam · 1.2 Syntax · 1.3 Veri · 1.4 Kontrol · 1.5 Fonksiyon · 1.6 Hata · 1.7 Dosya
▶
// 1.1 — KURULUM & ORTAM
Python Kurulumu
python.org → 3.12+ indir. Terminalde: python --version ile kontrol.
VS Code
Python extension kur. Pylance + Black formatter. .venv otomatik tanıma.
Terminal
cd, ls, mkdir, cp, mv komutları. Bash scripting temeli. Python burada çalışır.
// 1.2 — TEMEL SYNTAX
# Değişkenler — type hinting ile (önerilen)
isim: str = "Emre"
yas: int = 25
boy: float = 1.78
aktif: bool = True
# Input / Output
ad = input("Adın: ")
print(f"Merhaba {ad}!") # f-string
print(f"{yas = }") # debug shorthand: yas = 25
# Type dönüşüm
sayi = int(input("Sayı: "))
metin = str(42)
type(sayi) # <class 'int'>
// 1.3 — VERİ YAPILARI
# List — mutable, ordered, indexed
renkler: list[str] = ["kırmızı", "mavi", "yeşil"]
renkler.append("sarı")
renkler[0] # "kırmızı"
renkler[-1] # "yeşil" — sondan
renkler[1:3] # ["mavi", "yeşil"] — slice
# Tuple — immutable, coordinates, RGB vs.
nokta: tuple[int, int] = (10, 20)
x, y = nokta # unpacking
# Dictionary — key:value, mutable, O(1) lookup
kullanici: dict = {
"isim": "Ali", "yas": 22,
"aktif": True
}
kullanici.get("sehir", "bilinmiyor") # KeyError yok
# Set — unique, unordered
tekrarlar = {1, 2, 2, 3} # {1, 2, 3}
Mutable vs Immutable: List, Dict, Set → mutable (değişebilir). Tuple, String, Int → immutable. Bu fark fonksiyona argüman geçerken kritik — mutable'lar referans ile geçer!
// 1.4 — KONTROL YAPILARI
# if/elif/else — walrus operator ile (Python 3.8+)
if (n := int(input("Sayı: "))) > 0:
print(f"{n} pozitif")
elif n == 0:
print("sıfır")
else:
print(f"{n} negatif")
# for — enumerate, zip, range
for i, renk in enumerate(renkler, start=1):
print(f"{i}. {renk}")
for isim, puan in zip(isimler, puanlar):
print(f"{isim}: {puan}")
# while — break, continue, else
deneme = 0
while deneme < 3:
sifre = input("Şifre: ")
if sifre == "1234": break
deneme += 1
else:
print("Hesap kilitlendi") # break olmadan bittiyse
// 1.5 — FONKSİYONLAR
# Type hint + docstring
def vmi_hesapla(kilo: float, boy: float) -> float:
"""
BMI hesaplar.
Args: kilo (kg), boy (metre)
Returns: BMI değeri
"""
return kilo / (boy ** 2)
# *args ve **kwargs
def topla(*sayilar: int) -> int:
return sum(sayilar)
def kullanici_olustur(**bilgiler):
return {"id": id(bilgiler), **bilgiler}
# Lambda — kısa, tek satır
kare = lambda x: x ** 2
sirala = sorted(kullanicilar, key=lambda u: u["yas"])
// 1.6 & 1.7 — HATA YÖNETİMİ & DOSYA
# Özel exception sınıfı
class YasHatasi(ValueError):
pass
try:
yas = int(input("Yaş: "))
if yas < 0: raise YasHatasi("Negatif yaş olamaz")
except ValueError as e:
print(f"Geçersiz giriş: {e}")
finally:
print("İşlem tamamlandı") # her durumda çalışır
# Dosya işlemleri — context manager (en iyi yöntem)
with open("veri.json", "r", encoding="utf-8") as f:
veri = json.load(f) # otomatik kapatır
with open("cikti.txt", "w") as f:
json.dump(veri, f, ensure_ascii=False, indent=2)
🧮 Hesap Makinesi
✅ To-Do (CLI)
📝 Not Uygulaması
🔑 Şifre Üretici
2
// ORTA SEVİYE · INTERMEDIATE
OOP · Modüller · venv · List Comp · API · SQLite
2.1 OOP · 2.2 Modüller · 2.3 venv · 2.4 İleri Yapılar · 2.5 Stdlib · 2.6 API · 2.7 DB
▶
// 2.1 — OOP
⚠️ Kritik: Bu kısmı öğrenmeden ileri gidemezsin. OOP = büyük projeleri yönetmenin tek yolu.
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@dataclass
class Kullanici:
isim: str
yas: int
email: str
roller: list[str] = field(default_factory=list)
_sifre: str = field(default="", repr=False)
def __post_init__(self):
if self.yas < 0:
raise ValueError("Yaş negatif olamaz")
@property
def sifre(self) -> str:
return "***" # encapsulation
@sifre.setter
def sifre(self, deger: str):
self._sifre = hash_sifre(deger) # setter
@classmethod
def json_den_olustur(cls, veri: dict) -> "Kullanici":
return cls(**veri) # factory method
# Inheritance
class Admin(Kullanici):
yetkiler: list[str] = field(default_factory=list)
def yetki_ver(self, kullanici: Kullanici, yetki: str):
kullanici.roller.append(yetki)
# Polymorphism + Abstract
class Bildirim(ABC):
@abstractmethod
def gonder(self, mesaj: str) -> bool: ...
class EmailBildirim(Bildirim):
def gonder(self, mesaj: str) -> bool:
# SMTP ile gönder...
return True
// 2.4 — İLERİ VERİ YAPILARI
# List Comprehension — Pythonic yol
kareler = [x**2 for x in range(10)]
ciftler = [x for x in kareler if x % 2 == 0]
dict_comp = {k: v**2 for k, v in veriler.items()}
# Generator — lazy, bellek dostu
def fibonacci(n: int):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Generator expression
toplam = sum(x**2 for x in range(1_000_000))
# list'e çevirmek 8MB ram yer — generator: ~100 byte
# Iterator protokolü
class GeriSay:
def __init__(self, n): self.n = n
def __iter__(self): return self
def __next__(self):
if self.n <= 0: raise StopIteration
self.n -= 1; return self.n + 1
// 2.6 — API & 2.7 — DATABASE
import requests, sqlite3
# requests — HTTP client
res = requests.get(
"https://api.github.com/users/python",
headers={"Accept": "application/vnd.github+json"},
timeout=10
)
res.raise_for_status() # 4xx/5xx → exception
data = res.json()
# SQLite — CRUD
with sqlite3.connect("uygulama.db") as con:
con.execute("""
CREATE TABLE IF NOT EXISTS kullanicilar (
id INTEGER PRIMARY KEY AUTOINCREMENT,
isim TEXT NOT NULL,
email TEXT UNIQUE
)""")
con.execute(
"INSERT INTO kullanicilar (isim, email) VALUES (?, ?)",
("Ali", "ali@ornek.com") # ? ile SQL injection engelle
)
🌤️ API Veri Uygulaması
📰 Blog Backend
🔐 CLI Password Manager
📁 Dosya Organizasyon Scripti
3
// İLERİ SEVİYE · ADVANCED
Async · Threading · Design Patterns · Testing · Logging
3.1 Async · 3.2 Thread/Process · 3.3 Patterns · 3.4 Test · 3.5 Log · 3.6 Perf · 3.7 Güvenlik
▶
import asyncio, aiohttp
from typing import AsyncGenerator
# Async/Await — I/O bound işlemler için
async def veri_getir(session: aiohttp.ClientSession, url: str) -> dict:
async with session.get(url) as res:
return await res.json()
async def paralel_getir(urls: list[str]) -> list[dict]:
async with aiohttp.ClientSession() as session:
gorevler = [veri_getir(session, url) for url in urls]
return await asyncio.gather(*gorevler)
# 10 istek sıralı: 10s → paralel: ~1s
# Threading vs Multiprocessing
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# I/O bound → Thread (GIL önemli değil)
with ThreadPoolExecutor(max_workers=10) as ex:
sonuclar = list(ex.map(istek_at, url_listesi))
# CPU bound → Process (GIL bypass)
with ProcessPoolExecutor() as ex:
sonuclar = list(ex.map(hesapla, veri_listesi))
# Design Patterns
# Singleton — tek instance
class Config:
_instance: "Config | None" = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
# Observer — event sistemi
class EventBus:
_dinleyiciler: dict[str, list] = {}
def abone_ol(self, olay: str, fn): self._dinleyiciler.setdefault(olay, []).append(fn)
def yayinla(self, olay: str, **veri):
for fn in self._dinleyiciler.get(olay, []): fn(**veri)
# pytest ile test
import pytest
def test_vmi_hesapla():
assert vmi_hesapla(70, 1.75) == pytest.approx(22.86, abs=0.01)
def test_negatif_yas():
with pytest.raises(ValueError): Kullanici("Ali", -1, "a@b.com")
@pytest.mark.asyncio
async def test_api(httpx_mock):
httpx_mock.add_response(json={"id": 1})
result = await veri_getir("/api/user")
assert result["id"] == 1
Logging
logging.getLogger(__name__). DEBUG/INFO/WARNING/ERROR/CRITICAL seviyeleri. JSON formatter ile structured log.
Profiling
cProfile + snakeviz ile görsel analiz. line_profiler ile satır bazlı. memory_profiler ile RAM.
Input Validation
Pydantic ile şema validasyonu. Type coercion. Custom validator. FastAPI ile tam entegrasyon.
Encryption
hashlib ile SHA-256. bcrypt ile şifre hash. cryptography kütüphanesi. Fernet symmetric.
💬 Chat Server
⏰ Task Scheduler
🕷️ Web Scraper
🚦 API Rate Limiter
4
// UZMANLAŞMA · EN KRİTİK NOKTA
Backend · Data Science · Automation · Oyun
Bir alan seç — her şeyi öğrenemezsin. Derinleş.
▶
⚠️ Yol Ayrımı: Buradan sonra bir alan seçmen lazım. Her şeyi öğrenmeye çalışmak = hiçbirini öğrenememek. Güçlü yönünü bul, oraya yoğunlaş.
// 4.1 — BACKEND DEVELOPMENT
# FastAPI — modern, hızlı, async
from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
app = FastAPI(title="API", version="1.0")
class KullaniciOlustur(BaseModel):
isim: str
email: str
yas: int
@app.post("/kullanicilar", status_code=201)
async def kullanici_olustur(
veri: KullaniciOlustur,
db: AsyncSession = Depends(get_db)
):
kullanici = await kullanici_servisi.olustur(db, veri)
return kullanici
// 4.2 — VERİ BİLİMİ & AI
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# Pandas — veri işleme
df = pd.read_csv("veri.csv")
df.dropna().drop_duplicates()
df["yaslar"].describe() # istatistik
df.groupby("sehir")["gelir"].mean()
# Scikit-learn — ML
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestClassifier().fit(X_train, y_train)
model.score(X_test, y_test) # accuracy
// 4.4 — AUTOMATION & SCRAPING
from selenium import webdriver
from selenium.webdriver.common.by import By
from playwright.async_api import async_playwright
import httpx, bs4
# Modern scraping — Playwright (headless)
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto("https://example.com")
baslik = await page.inner_text("h1")
# httpx + BeautifulSoup — statik sayfa
res = httpx.get("https://news.ycombinator.com")
soup = bs4.BeautifulSoup(res.text, "html.parser")
basliklar = [a.text for a in soup.select(".titleline a")]
4.3 Siber Güvenlik (Python)
Network programming, socket API, şifreleme kütüphaneleri (cryptography), güvenlik araçları geliştirme. Savunma odaklı: log analizi, anomali tespiti.
4.5 Oyun Geliştirme
Pygame ile 2D oyun. Sprite, collision, game loop, event handling. Basit platformer veya top oyunu ile başla.
5
// GERÇEK DÜNYA & PROFESYONEL
Git · Linux · Algoritmalar · Clean Code · Sistem Tasarımı
5.1 Git/GitHub · 5.2 Linux · 5.3 Algo · 6. Pro Level
▶
# Clean Code — Pythonic yazım
# ❌ Kötü
def f(x, y, z):
r = []
for i in x:
if i[y] > z:
r.append(i)
return r
# ✅ İyi — type hints, anlamlı isimler
def yasa_gore_filtrele(
kullanicilar: list[dict],
alan: str,
esik: int
) -> list[dict]:
"""Belirtilen alana göre kullanıcıları filtreler."""
return [u for u in kullanicilar if u[alan] > esik]
# Algoritmalar — sorting örneği
def quicksort(dizi: list) -> list:
if len(dizi) <= 1: return dizi
pivot = dizi[len(dizi) // 2]
sol = [x for x in dizi if x < pivot]
orta = [x for x in dizi if x == pivot]
sag = [x for x in dizi if x > pivot]
return quicksort(sol) + orta + quicksort(sag)
Git Workflow
Feature branch → PR → Code review → merge. Conventional commits. .gitignore. GitHub Actions CI.
Linux Terminal
grep, awk, sed, find, chmod, cron. Bash scripting. systemd service. Log yönetimi.
Sistem Tasarımı
Cache (Redis), Queue (Celery/RabbitMQ), Load balancer. Scalability pattern'leri. Database sharding.