How does the loop check divisibility?

QuestionsQuestions4 SkillsProPython Control StructuresNov, 12 2025
0107

The loop checks divisibility using the modulus operator %. Here's how it works in the context of the code:

Code Context:

for i in range(2, num):
    if num % i == 0:
        print(f"{num} is not prime")
        break

Explanation:

  1. Modulus Operator %: This operator returns the remainder of the division of num by i.

    • For example, num % i calculates how much is left over when num is divided by i.
  2. Divisibility Check: The condition if num % i == 0 checks if the remainder is zero.

    • If num % i == 0, it means that num is divisible by i without any remainder, indicating that i is a divisor of num.

Example:

  • Suppose num = 6 and the loop iterates with i taking values from 2 to 5:
    • For i = 2: 6 % 2 equals 0 (6 is divisible by 2).
      • The condition is true, so it prints "6 is not prime" and breaks out of the loop.
    • For i = 3: 6 % 3 equals 0 (6 is divisible by 3).
      • Again, the condition is true, but the loop has already exited.

Conclusion:

If the loop finds any i such that num % i == 0, it concludes that num is not a prime number. If no such i is found by the end of the loop, num is considered prime.

If you have further questions or need more examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!