Python Forum
python example has me puzzled
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python example has me puzzled
#1
Shocked 
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)
Reply
#2
(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)
Recommended Tutorials:
Reply
#3
(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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020