Bird
Raised Fist0

You want to add a custom attribute status to multiple instances of a class Task only if their priority is above 5. Which code correctly does this?

hard🚀 Application Q15 of Q15
Python - Custom Exceptions
You want to add a custom attribute status to multiple instances of a class Task only if their priority is above 5. Which code correctly does this?
Afor t in tasks: if t.priority > 5: t.status = 'urgent'
Bfor t in tasks: t.status = 'urgent' if t.priority > 5 else None
Cfor t in tasks: if t.priority > 5: t['status'] = 'urgent'
Dfor t in tasks: t.status = 'urgent' if t.priority <= 5: del t.status
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition and attribute addition

    We want to add status only if priority > 5, so we check this condition inside the loop.
  2. Step 2: Check each option's logic and syntax

    for t in tasks: if t.priority > 5: t.status = 'urgent' adds status only when priority > 5 using dot notation correctly. for t in tasks: t.status = 'urgent' if t.priority > 5 else None assigns status to None for others, which adds the attribute unnecessarily. for t in tasks: if t.priority > 5: t['status'] = 'urgent' uses dictionary syntax which is invalid. for t in tasks: t.status = 'urgent' if t.priority <= 5: del t.status adds status to all then deletes for low priority, which is inefficient and error-prone.
  3. Final Answer:

    for t in tasks: if t.priority > 5: t.status = 'urgent' -> Option A
  4. Quick Check:

    Use if condition and dot notation to add attributes selectively [OK]
Quick Trick: Add attributes inside if-block with dot notation [OK]
Common Mistakes:
MISTAKES
  • Using dictionary syntax on objects
  • Adding attribute to all instances regardless of condition
  • Assigning None instead of skipping attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes