Python Forum

Full Version: python example has me puzzled
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can't figure out how the program at:

https://www.programiz.com/python-program...-intervals

is working, but when I copy/paste it into spyder it does indeed work. To my poor eyes, the else is not indented with either of the 2 if statements. In fact, how can one really tell which one it goes with?

I know the numbers are right, since I asked wolfram alpha for the primes between 900 and 1000 and got the same answer that they print out on the website (above) as well as it comes out of spyder. Please explain?


lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):
   # all prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num)
(Jan-21-2021, 12:03 AM)rocket777 Wrote: [ -> ]the else is not indented with either of the 2 if statements
for loops can have else clauses too. else Runs if and only if the loop is exited normally (i.e, without running into a break)
(Jan-21-2021, 12:31 AM)metulburr Wrote: [ -> ]
(Jan-21-2021, 12:03 AM)rocket777 Wrote: [ -> ]the else is not indented with either of the 2 if statements
for loops can have else clauses too. else Runs if and only if the loop is exited normally (i.e, without running into a break)

Thanks, I guess old dogs have trouble learning new tricks. 40 years in the business, never saw any other language with that. I guess it saves needing a flag variable.