Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else block without if block in python [duplicate]

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))
like image 259
Hasnain Ali Avatar asked Feb 19 '26 13:02

Hasnain Ali


1 Answers

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))
like image 108
Bigbob556677 Avatar answered Feb 22 '26 02:02

Bigbob556677



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!