1

I found the Python Code snippet online to print the range of the prime number but the last else block is making no sense to me as it doesn't has corresponding if block

Note The Indentation of else block is intentional as it work correctly the way it is and i come up with this code after watching the tutorial on youtube at https://www.youtube.com/watch?v=KdiWcJscO_U

entry_value = int(input("Plese enter the starting value:"))
ending_value = int(input("Plese enter the ending value:"))
for i in range(entry_value, ending_value+1):
    if i>1:
        for j in range(2,i):
            if i%j == 0:
                break
        else:
            print("{} is prime number".format(i))
Hasnain Ali
  • 133
  • 5
  • 1
    The indentation of this code is just wrong. – takendarkk Apr 30 '21 at 16:08
  • Indentation of this else statement is intentional i come up with this code from the video https://www.youtube.com/watch?v=KdiWcJscO_U – Hasnain Ali Apr 30 '21 at 16:13
  • Nothing wrong with the indentation, this is a good example of the rarely used for/else logic. – William D. Irons Apr 30 '21 at 16:13
  • 1
    @jps I think the indentation is actually correct since `if i%j == 0` it's not a prime number. It just seems like a weird way to program that, kinda backwards. – Bigbob556677 Apr 30 '21 at 16:14
  • 1
    Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Woodford Apr 30 '21 at 16:44

1 Answers1

5

Python (and other languages) use an else block to specify code that runs only if the for loop was completed, and not broken out of.

In your code, if i%j == 0 the loop will exit, but the else code will not be called.

Here is an example with comments:

for x in range(2,i):
    if i%j == 0:
        break #number is not prime so we break and don't call else
else:
    print("{} is prime number".format(i))
Bigbob556677
  • 1,805
  • 1
  • 13
  • 38