Python programlamada karşılaştığınız hataları çözün, debugging teknikleri öğrenin ve "Nasıl Yapılır" rehberleri ile becerilerinizi geliştirin.
Python'da en sık karşılaşılan hatalardan biri. Girinti (indentation) hatası nasıl çözülür?
if x > 5:
print("Büyük sayı") # IndentationError!
if x > 5:
print("Büyük sayı") # Doğru girinti (4 boşluk)
# Veya tab kullanarak:
if x > 5:
print("Büyük sayı") # 1 tab
Python'da girinti çok önemli! Her zaman 4 boşluk veya 1 tab kullanın, karıştırmayın.
Liste sınırları dışında erişim hatası ve güvenli erişim yöntemleri.
liste = [1, 2, 3]
print(liste[5]) # IndexError: list index out of range
liste = [1, 2, 3]
# Yöntem 1: Uzunluğu kontrol et
if len(liste) > 5:
print(liste[5])
else:
print("Liste çok kısa!")
# Yöntem 2: try-except kullan
try:
print(liste[5])
except IndexError:
print("Geçersiz indeks!")
# Yöntem 3: get() benzeri fonksiyon
def safe_get(lst, index, default=None):
return lst[index] if 0 <= index < len(lst) else default
print(safe_get(liste, 5, "Bulunamadı")) # "Bulunamadı"
Metin dosyalarını güvenli şekilde okuma, yazma ve işleme rehberi.
# Temel dosya okuma
with open('dosya.txt', 'r', encoding='utf-8') as f:
icerik = f.read()
print(icerik)
# Satır satır okuma
with open('dosya.txt', 'r', encoding='utf-8') as f:
for satir in f:
print(satir.strip()) # strip() ile boşlukları temizle
# Dosyaya yazma
veriler = ["Python", "öğreniyorum", "çok", "eğlenceli"]
with open('yeni_dosya.txt', 'w', encoding='utf-8') as f:
for veri in veriler:
f.write(veri + '\n')
# JSON dosyası ile çalışma
import json
# JSON yazma
data = {"ad": "Ahmet", "yas": 25, "sehir": "İstanbul"}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# JSON okuma
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data["ad"])
Web API'lerinden veri çekme, hata yönetimi ve JSON işleme.
import requests
import json
# Basit GET isteği
response = requests.get('https://api.github.com/users/octocat')
if response.status_code == 200:
data = response.json()
print(f"Kullanıcı: {data['name']}")
print(f"Takipçi sayısı: {data['followers']}")
else:
print(f"Hata: {response.status_code}")
# POST isteği (veri gönderme)
user_data = {
"name": "Ahmet",
"email": "ahmet@example.com"
}
response = requests.post(
'https://api.example.com/users',
json=user_data,
headers={'Content-Type': 'application/json'}
)
# Hata yönetimi ile güvenli API çağrısı
def api_request(url, timeout=5):
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status() # HTTP hata durumunda exception fırlat
return response.json()
except requests.exceptions.ConnectionError:
return {"error": "Bağlantı hatası"}
except requests.exceptions.Timeout:
return {"error": "Zaman aşımı"}
except requests.exceptions.HTTPError as e:
return {"error": f"HTTP hatası: {e}"}
except requests.exceptions.RequestException as e:
return {"error": f"İstek hatası: {e}"}
# Kullanım
result = api_request('https://api.github.com/users/octocat')
if 'error' in result:
print(result['error'])
else:
print(f"API'den alınan veri: {result['name']}")
Büyük veri setleri ile çalışırken bellek kullanımını optimize etme teknikleri.
# Yanlış: Tüm veriyi belleğe yükler
def process_large_file(filename):
with open(filename, 'r') as f:
lines = f.readlines() # Tüm dosya belleğe yüklenir!
results = []
for line in lines:
results.append(line.upper())
return results
# Doğru: Generator kullanarak bellek tasarrufu
def process_large_file_optimized(filename):
def line_processor():
with open(filename, 'r') as f:
for line in f: # Her seferinde tek satır okur
yield line.upper()
return line_processor()
# Liste comprehension yerine generator expression
def get_squares(numbers):
return (x**2 for x in numbers) # Generator (lazy evaluation)
# Büyük listeler için __slots__ kullanımı
class OptimizedPerson:
__slots__ = ['name', 'age', 'email'] # Bellek tasarrufu
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
# Pandas ile büyük dosyalar
import pandas as pd
# Chunk halinde okuma
def process_large_csv(filename, chunk_size=1000):
for chunk in pd.read_csv(filename, chunksize=chunk_size):
# Her chunk'ı ayrı ayrı işle
processed_chunk = chunk.groupby('category').sum()
yield processed_chunk
# Memory profiling
import tracemalloc
tracemalloc.start()
# Kodunuz buraya...
current, peak = tracemalloc.get_traced_memory()
print(f"Mevcut bellek: {current / 1024 / 1024:.1f} MB")
print(f"Peak bellek: {peak / 1024 / 1024:.1f} MB")
tracemalloc.stop()
Kodunuzdaki hataları bulma ve çözme için profesyonel debugging yöntemleri.
import pdb
import logging
# 1. Print debugging (basit ama etkili)
def problematic_function(numbers):
print(f"Gelen veri: {numbers}") # Debug print
total = 0
for i, num in enumerate(numbers):
print(f"Adım {i}: {num} -> Toplam: {total}") # Her adımı izle
total += num
print(f"Sonuç: {total}")
return total
# 2. PDB debugger kullanımı
def debug_example():
x = 10
y = 5
pdb.set_trace() # Breakpoint - kod burada durur
result = x / y
return result
# 3. Logging ile profesyonel debugging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def calculate_average(numbers):
logging.debug(f"calculate_average çağrıldı: {numbers}")
if not numbers:
logging.error("Boş liste gönderildi!")
return None
total = sum(numbers)
average = total / len(numbers)
logging.info(f"Ortalama hesaplandı: {average}")
return average
# 4. Exception handling ile debugging
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError as e:
logging.error(f"Sıfıra bölme hatası: {a} / {b}")
raise
except Exception as e:
logging.error(f"Beklenmeyen hata: {e}")
raise
# 5. Assert kullanımı
def validate_input(value):
assert isinstance(value, int), f"Değer integer olmalı, {type(value)} verildi"
assert value > 0, f"Değer pozitif olmalı, {value} verildi"
return value * 2
# 6. Decorator ile fonksiyon izleme
def debug_decorator(func):
def wrapper(*args, **kwargs):
print(f"Çağrılan fonksiyon: {func.__name__}")
print(f"Argümanlar: {args}, {kwargs}")
result = func(*args, **kwargs)
print(f"Sonuç: {result}")
return result
return wrapper
@debug_decorator
def multiply(x, y):
return x * y
Python projeleriniz için izole çalışma ortamları oluşturma rehberi.
# Virtual environment oluşturma
python -m venv myproject
# Windows'ta aktifleştirme
myproject\Scripts\activate
# Mac/Linux'ta aktifleştirme
source myproject/bin/activate
# Kütüphane yükleme
pip install requests pandas numpy
# Requirements dosyası oluşturma
pip freeze > requirements.txt
# Requirements'tan yükleme
pip install -r requirements.txt
# Deaktif etme
deactivate
Her proje için ayrı virtual environment kullanın. Bu şekilde kütüphane çakışmalarını önlersiniz.
Metin işleme, temizleme ve dönüştürme teknikleri.
# Temel string işlemleri
text = " Python Programlama Dilini Öğreniyorum "
# Temizleme işlemleri
clean_text = text.strip() # Baştaki ve sondaki boşlukları sil
lower_text = text.lower() # Küçük harfe çevir
upper_text = text.upper() # Büyük harfe çevir
title_text = text.title() # İlk harfleri büyük yap
# String arama ve değiştirme
if "Python" in text:
print("Python bulundu!")
new_text = text.replace("Python", "Java")
index = text.find("Programlama") # Kelimeyi bulur, -1 döner bulamazsa
# String bölme ve birleştirme
words = text.strip().split() # Kelimelere böl
sentence = " ".join(words) # Kelimeleri birleştir
# Format işlemleri
name = "Ahmet"
age = 25
city = "İstanbul"
# f-string (Python 3.6+)
message = f"Merhaba {name}, {age} yaşındasın ve {city}'da yaşıyorsun."
# .format() metodu
message = "Merhaba {}, {} yaşındasın ve {}'da yaşıyorsun.".format(name, age, city)
# % formatting (eski stil)
message = "Merhaba %s, %d yaşındasın." % (name, age)
# String validasyon
def validate_email(email):
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
# Türkçe karakter dönüşümü
def turkce_normalize(text):
turkce_chars = "çğıöşüÇĞIÖŞÜ"
english_chars = "cgiosucgIOSU"
trans_table = str.maketrans(turkce_chars, english_chars)
return text.translate(trans_table)
# String encoding/decoding
text = "Türkçe karakterler: çğıöşü"
encoded = text.encode('utf-8')
decoded = encoded.decode('utf-8')
Karşılaştığınız problemi burada bulamadıysanız, kod editörümüzde deneyin veya topluluk desteği alın.