Bird
0
0

Find the error in this code:

medium📝 Debug Q14 of 15
Python - For Loop
Find the error in this code:
text = "hello"
for i in text:
    print(text[i])
AVariable 'text' is not defined
BMissing colon after for loop
CLoop should be 'for i in range(text):'
DUsing 'i' as index causes TypeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop variable 'i'

    Here, 'i' takes each character from 'text', so 'i' is a letter, not an index.
  2. Step 2: Using 'text[i]' causes error

    Since 'i' is a letter, using it as an index causes a TypeError because string indices must be integers.
  3. Final Answer:

    Using 'i' as index causes TypeError -> Option D
  4. Quick Check:

    Loop variable is letter, not index, so indexing fails [OK]
Quick Trick: Loop variable is letter, not index; use range(len(text)) for indices [OK]
Common Mistakes:
MISTAKES
  • Assuming loop variable is index
  • Trying to index string with a character
  • Confusing loop variable with range

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes