3

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))
5
  • 1
    The indentation of this code is just wrong.
    – takendarkk
    Commented Apr 30, 2021 at 16:08
  • Indentation of this else statement is intentional i come up with this code from the video youtube.com/watch?v=KdiWcJscO_U Commented Apr 30, 2021 at 16:13
  • Nothing wrong with the indentation, this is a good example of the rarely used for/else logic. Commented Apr 30, 2021 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. Commented Apr 30, 2021 at 16:14
  • 2
    Does this answer your question? Why does python use 'else' after for and while loops?
    – Woodford
    Commented Apr 30, 2021 at 16:44

1 Answer 1

7

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))
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.