Bird
0
0

You want to check a list of numbers to ensure all are positive using assert. Which code correctly uses assert inside a loop to do this?

hard📝 Application Q15 of 15
Python - Advanced Exception Handling
You want to check a list of numbers to ensure all are positive using assert. Which code correctly uses assert inside a loop to do this?
nums = [3, 5, -1, 7]
for n in nums:
    ?
Aassert n > 0; f"Number {n} is not positive"
Bassert n > 0: f"Number {n} is not positive"
Cassert n > 0, f"Number {n} is not positive"
Dassert (n > 0), "Number n is not positive"
Step-by-Step Solution
Solution:
  1. Step 1: Understand assert in loop context

    We want to check each number and stop if any is not positive, showing which one failed.
  2. Step 2: Check syntax correctness

    assert n > 0, f"Number {n} is not positive" uses correct assert syntax with a comma and f-string for message. Others use invalid punctuation.
  3. Final Answer:

    assert n > 0, f"Number {n} is not positive" -> Option C
  4. Quick Check:

    Assert syntax: condition, message with comma [OK]
Quick Trick: Use comma and f-string for assert message in loops [OK]
Common Mistakes:
  • Using colon or semicolon instead of comma
  • Not using f-string for variable message
  • Putting message outside assert statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes