DE EN

AI Co-Coding

Systematic prompting for Python, code review with AI, efficient debugging strategies.

60 Min Schwer

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:

  1. Context: Who are you, what can you do?

  2. Requirement: What exactly should be done?

  3. Format: How should the answer look?

  4. Constraints: What should be avoided?

Python
# 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))
Ausgabe
Länge schlecht: 23 Länge gut: 342

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?"
Python
# 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)
Ausgabe
Reviewe die Funktion berechalt(). - Prüfe auf Bugs (z.B. negative Preise, Prozent > 100) ...

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.

Python
# 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)
Ausgabe
Ich bekomme diesen Fehler: TypeError: unsupported operand type(s) for /: 'int' and 'list' ...

AI Refactoring in Practice

Refactoring means: improving code without changing its behavior. AI can help you transform unreadable code into clean, pythonic solutions.

Python
# 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)}")
Ausgabe
95% = Note 1 82% = Note 2 70% = Note 3 55% = Note 4 40% = Note 5
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
def note_von_prozent(p):
    if p >= 89: return 1
    if p >= 76: return 2
    ...
JavaScript
function noteVonProzent(p) {
    if (p >= 89) return 1;
    if (p >= 76) return 2;
    ...
}
Merke: The original if-elif pattern is identical in Python and JavaScript. The AI improvement with the threshold list shows pythonic thinking — less repetition, more readability.

PyBuddy Meets AI

PyBuddy gets a function that generates structured AI prompts. The user enters a topic, PyBuddy creates a perfect prompt for it.

Python
# 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)
Ausgabe
Welches Thema willst du lernen? Schleifen Dein KI-Prompt: ======================================== Erkläre mir das Thema 'Schleifen' in Python. Zielgruppe: Anfänger (15-19 Jahre) ... ========================================

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)

Solution
# 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)

Solution
# 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()

Solution
# 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()
Didactic Break

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