Bird
0
0

This code is meant to filter AI output for banned words but causes an error:

medium📝 Debug Q14 of 15
Agentic AI - Agent Safety and Guardrails
This code is meant to filter AI output for banned words but causes an error:
output = "Safe text"
banned_words = ["bad", "ugly"]
for word in banned_words:
    if output.index(word):
        print("Banned word found")
        break
What is the error and how to fix it?
ASyntax error due to missing colon after for loop
Bindex() raises ValueError if word not found; use 'in' instead
CTypeError because output is not a list
DNo error; code works fine
Step-by-Step Solution
Solution:
  1. Step 1: Identify the error cause

    Using output.index(word) raises ValueError if word is not found in output string.
  2. Step 2: Suggest fix

    Replace 'output.index(word)' with 'word in output' to safely check containment without error.
  3. Final Answer:

    index() raises ValueError if word not found; use 'in' instead -> Option B
  4. Quick Check:

    index() error fixed by 'in' check [OK]
Quick Trick: Use 'in' to check substring safely, not index() [OK]
Common Mistakes:
  • Ignoring ValueError from index()
  • Thinking output must be a list
  • Missing colons in loops (not in this code)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Agentic AI Quizzes