-2

What does it mean when if else statement in different row,I had tried it in same row but the result is different.

num = 407

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

2 Answers2

1

The else statement in your code:

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

is only executed because there was no break in your for loop, because your for loop only breaks out if the if statement is True:

...
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
...

This would mean that writing your code like this:

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

would give you the same output, if you wrote your code like this, with the else statement only executing if the if statement was proven False:

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

To read more about else statements at the end of for loops, visit:

https://www.geeksforgeeks.org/using-else-conditional-statement-with-for-loop-in-python/

topsoftwarepro
  • 773
  • 5
  • 19
0

Your indentation matters in Python.

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.

Reference this article for more information: https://docs.python.org/2.0/ref/indentation.html

I'll be happy to answer any further questions you have.

ttodorov
  • 32
  • 4