Lernziele dieses Kapitels
- You write effective prompts for Python code with AI
- You critically review AI-generated code and improve it
- You use AI-assisted debugging for quick error fixing
- You extend PyBuddy with an AI prompt generator
Effective Prompting
Good prompts are like good assignments: specific, structured, and rich in context. Instead of "Write me a game" you say: "Create a number guessing game in Python with input(), random numbers, and a guess counter. Comment the code."
The best structure for prompts:
Context: Who are you, what can you do?
Requirement: What exactly should be done?
Format: How should the answer look?
Constraints: What should be avoided?
# Schlechter vs. guter Prompt (als String)
schlecht = "Schreib mir ein Programm"
gut = '''Ich bin 16 Jahre alt und lerne Python.
Erstelle ein Zahlenratespiel mit folgenden Anforderungen:
- Nutze random.randint() für eine Zahl 1-100
- Der Spieler gibt Tipps ein
- Nach jedem Tipp kommt "zu hoch" oder "zu niedrig"
- Zähle die Versuche
- Gib am Ende die Anzahl der Versuche aus
- Kommentiere den Code für Anfänger
Format: Nur Python-Code, keine Erklärungen dazwischen.'''
print("Länge schlecht:", len(schlecht))
print("Länge gut:", len(gut))
Code Review with AI
AI is an excellent code reviewer — if you ask the right questions. Ask the AI to check your code for bugs, security vulnerabilities, and best practices.
Typical review questions:
- "Review this function for bugs and edge cases."
- "Check for Python best practices (PEP 8)."
- "Are there security issues?"
- "How can I make the code more efficient?"
# Beispiel-Code für ein KI-Review
def berechne_rabatt(preis, prozent):
return preis - (preis * prozent / 100)
# KI-Prompt:
review_prompt = '''
Reviewe die Funktion berechne_rabatt().
- Prüfe auf Bugs (z.B. negative Preise, Prozent > 100)
- Schlage Input-Validierung vor
- Formatiere nach PEP 8
- Gib den verbesserten Code als Komplettlösung aus
'''
print(review_prompt)
AI-Assisted Debugging
When your code doesn't work, copy error message + code into the AI. The best question is specific: "I get [ERROR]. Here is my code. Explain to me why and how I fix it."
Pro Tip
Always provide the complete error text and the relevant code snippet. Without context, the AI can only guess.
# Beispiel für KI-Debugging-Request
fehler_code = '''
noten = [2, 3, 1, 4]
durchschnitt = sum(noten) / len(noten)
print(f"Durchschnitt: {durchschnitt:.2f}")
'''
fehlermeldung = "TypeError: unsupported operand type(s) for /: 'int' and 'list'"
debug_prompt = f'''
Ich bekomme diesen Fehler:
{fehlermeldung}
Hier ist mein Code:
{fehler_code}
Erkläre mir:
1. Warum tritt der Fehler auf?
2. Wie behebe ich ihn?
3. Zeige mir den korrigierten Code.
'''
print(debug_prompt)
AI Refactoring in Practice
Refactoring means: improving code without changing its behavior. AI can help you transform unreadable code into clean, pythonic solutions.
# Vorher: Unleserlicher Code
def note_von_prozent(p):
if p > 89:
return 1
if p > 76:
return 2
if p > 63:
return 3
if p > 50:
return 4
return 5
# Nach KI-Refactoring (besser):
def note_von_prozent(p):
"""Gibt die Schulnote (1-5) basierend auf Prozent zurück."""
if not (0 <= p <= 100):
raise ValueError("Prozent muss zwischen 0 und 100 liegen")
grenzen = [(89, 1), (76, 2), (63, 3), (50, 4)]
for grenze, note in grenzen:
if p >= grenze:
return note
return 5
# Test
for p in [95, 82, 70, 55, 40]:
print(f"{p}% = Note {note_von_prozent(p)}")
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
def note_von_prozent(p):
if p >= 89: return 1
if p >= 76: return 2
...
function noteVonProzent(p) {
if (p >= 89) return 1;
if (p >= 76) return 2;
...
}
PyBuddy Meets AI
PyBuddy gets a function that generates structured AI prompts. The user enters a topic, PyBuddy creates a perfect prompt for it.
# pybuddy/main.py
def ki_prompt(thema, zielgruppe="Anfänger", sprache="de"):
"""Generiert einen strukturierten KI-Prompt."""
prompt = f"""
Erkläre mir das Thema '{thema}' in Python.
Zielgruppe: {zielgruppe} (15-19 Jahre)
Sprache: {sprache}
Format: Code-Beispiel + Erklärung
Anforderungen:
- Nutze ein praktisches Beispiel
- Kommentiere den Code für Anfänger
- Zeige typische Fehler und wie man sie vermeidet
- Maximal 30 Zeilen Code
"""
return prompt.strip()
# Nutzung
thema = input(" Welches Thema willst du lernen? ")
prompt = ki_prompt(thema)
print("\n Dein KI-Prompt:")
print("=" * 40)
print(prompt)
print("=" * 40)
Warm-Up: AI Refactor Challenge
Take your grade calculator function from Chapter 4. Write a prompt that asks the AI to improve it with input validation, docstring, and type hints.
Hinweis: # Alter Code (aus Kapitel 4)
def note(p):
if p >= 89: return 1
elif p >= 76: return 2
elif p >= 63: return 3
elif p >= 50: return 4
else: return 5
# KI-Prompt:
prompt = '''Refactore diese Funktion mit:
1. Input-Validierung (0-100)
2. Docstring
3. Typ-Hinweise
4. PEP 8 Konformität
5. Test-Beispiele
Code:
def note(p):
if p >= 89: return 1
...'''
print(prompt)
# Alter Code (aus Kapitel 4)
def note(p):
if p >= 89: return 1
elif p >= 76: return 2
elif p >= 63: return 3
elif p >= 50: return 4
else: return 5
# KI-Prompt:
prompt = '''Refactore diese Funktion mit:
1. Input-Validierung (0-100)
2. Docstring
3. Typ-Hinweise
4. PEP 8 Konformität
5. Test-Beispiele
Code:
def note(p):
if p >= 89: return 1
...'''
print(prompt)
Challenge: Debugging Exercise
Write intentionally buggy code (e.g. IndexError, TypeError). Then write an AI prompt that contains the error message and code and asks for an explanation.
Hinweis: # Absichtlich fehlerhafter Code
code = "\nspieler = ['Anna', 'Ben']\nprint(spieler[5]) # IndexError!\n"
fehler = 'IndexError: list index out of range'
prompt = f'''\nIch bekomme diesen Fehler: {fehler}\n\nMein Code:{code}\n\nErkläre mir:\n1. Warum passiert das?\n2. Wie finde ich die Zeile mit dem Fehler?\n3. Wie behebe ich ihn sicher?\n'''
print(prompt)
# Absichtlich fehlerhafter Code
code = "\nspieler = ['Anna', 'Ben']\nprint(spieler[5]) # IndexError!\n"
fehler = 'IndexError: list index out of range'
prompt = f'''\nIch bekomme diesen Fehler: {fehler}\n\nMein Code:{code}\n\nErkläre mir:\n1. Warum passiert das?\n2. Wie finde ich die Zeile mit dem Fehler?\n3. Wie behebe ich ihn sicher?\n'''
print(prompt)
PyBuddy-Checkpoint: AI Integration
PyBuddy gets a function that asks the user for a topic and generates a structured prompt for AI tools.
Hinweis: # pybuddy/main.py
def ki_generator():
print(" PyBuddy KI-Assistent")
thema = input("Thema: ")
level = input("Level (Anfänger/Fortgeschritten/Pro): ") or "Anfänger"
prompt = f"""\nErkläre mir '{thema}' in Python.\nMein Level: {level}\nFormat: Kurzes Code-Beispiel + Erklärung\nAnforderungen:\n- Praxisnah und verständlich\n- Maximal 20 Zeilen Code\n- Tipps für häufige Fehler\n"""
print("\n Kopiere diesen Prompt in deine KI:")
print("-" * 40)
print(prompt)
print("-" * 40)
ki_generator()
# pybuddy/main.py
def ki_generator():
print(" PyBuddy KI-Assistent")
thema = input("Thema: ")
level = input("Level (Anfänger/Fortgeschritten/Pro): ") or "Anfänger"
prompt = f"""\nErkläre mir '{thema}' in Python.\nMein Level: {level}\nFormat: Kurzes Code-Beispiel + Erklärung\nAnforderungen:\n- Praxisnah und verständlich\n- Maximal 20 Zeilen Code\n- Tipps für häufige Fehler\n"""
print("\n Kopiere diesen Prompt in deine KI:")
print("-" * 40)
print(prompt)
print("-" * 40)
ki_generator()
In Portal 2 you program with visual blocks — the AI GLaDOS comments on your code. AI assistants have long been reality: GitHub Copilot, ChatGPT, Claude — they all help developers write better code faster. You are currently learning to use these tools professionally!
Zusammenfassung
- Good Prompts = Context + Requirement + Format + Constraints
- AI as Code Reviewer: Check bugs, security, best practices
- Debugging: Error message + Code → AI for quick help
- Refactoring with AI: Transform unreadable code into pythonic code
- PyBuddy now generates structured AI prompts