Bird
0
0

You want to check if a number is prime using a for-else loop. Which code correctly prints Prime if no divisor is found and Not prime if a divisor is found?

hard📝 Application Q8 of 15
Python - For Loop
You want to check if a number is prime using a for-else loop. Which code correctly prints Prime if no divisor is found and Not prime if a divisor is found?
Afor i in range(2, n): if n % i == 0: print('Prime') break else: print('Not prime')
Bfor i in range(2, n): if n % i == 0: print('Not prime') break else: print('Prime')
Cfor i in range(2, n): if n % i != 0: print('Not prime') break else: print('Prime')
Dfor i in range(2, n): if n % i == 0: print('Prime') else: print('Not prime')
Step-by-Step Solution
Solution:
  1. Step 1: Understand prime check logic

    If any number divides n evenly, n is not prime and loop breaks printing 'Not prime'.
  2. Step 2: Check else block usage

    If no divisor found (no break), else runs printing 'Prime'. for i in range(2, n): if n % i == 0: print('Not prime') break else: print('Prime') matches this logic correctly.
  3. Final Answer:

    for i in range(2, n): if n % i == 0: print('Not prime') break else: print('Prime') -> Option B
  4. Quick Check:

    Break on divisor, else prints prime [OK]
Quick Trick: Break on divisor found, else means prime [OK]
Common Mistakes:
MISTAKES
  • Swapping print messages for prime and not prime
  • Missing break causing multiple prints
  • Incorrect else placement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes