Home > Blockchain >  need to understand how the code is working
need to understand how the code is working

Time:01-20

num = 2
if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print(num, "is not a prime number")
            break
    else:
        print(num, "is a prime number")

else:
    print(num, "is not a prime number")

The above code works. I have an issue understanding the logic. When n=2, and the first iteration is run in the for loop, i=2,

so num=2,i=2. Therefore, num%i==0, and it should break and print '2 is not a prime number'

I am fairly new to coding. So, I appreciate all the help. Thank you.

CodePudding user response:

When num == 0 the for loop never enters since range(2, 2) just like range(0) is zero.

Now, your for loop has an else clause. This else clause hits in 2 cases: The for loop runs in full to the end without breaking somewhere in the middle or the for loop doesn't run at all, like in your case. These 2 cases are practically one case, in general. The else clause of a for loop hits when the loop runs in full, which not running at all because range(0) can be seen as a rewording of running successfully in full, because 0 is the full range of this for loop.

So, your code goes directly to the else clause of the for loop and the condition num%i==0 is never checked.

CodePudding user response:

The issue is that you're assuming that value is entering in the for loop. To clarify, if you run

for i in range(n,n):
    print(i)

You'll no receive any response.

So, since your code has a for-else condition is this case can be understood as:

if num>2:
   for i = 2 to num:
      checking
else:
 print "not a prime"

:)
For the rest of the code is just checking that any previous number (of num) can divide num.

  •  Tags:  
  • Related