0

The second code tries to print prime numbers between the range but it fails to do that and prints some numbers multiple times between the range The first code,where the indentation seems absurd runs perfectly and I don't understand how the indentation is working for this

for num in range(lower,upper + 1):     
   for i in range(2,num):
       if (num % i) == 0:
           break
   else:
         print(num)

for num in range(lower,upper + 1):     
   for i in range(2,num):
       if (num % i) == 0:
           break
       else:
           print(num)
Aegon
  • 25
  • 5

3 Answers3

3

Python has an else clause not only for if but also for loops as well. The for ... else clause triggers if the loop is not left forcefully - via return, raise or break - but iteration finishes normally.

for i in range(3):
    print(i)
else:
    print('done')

for i in range(5):
    print(i)
    if i == 3:
        break  # break skips the else clause
else:
    print('done')

For your code, this means:

  • In the first case, else triggers if none of the i trigger (num % i) == 0.
  • In the second case, else triggers if one (or more) of the i does not trigger (num % i) == 0.
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
1

The only thing "absurd" about the indentation of the first code is that the final print is indented more than needed.

else, when applied to a loop, is executed when the loop is exhausted (as opposed to broken out of). So in the first code, as long as num isn't divisible by any i, it will be printed, which is what you want.

else, when applied to an if, has no effect on the enclosing loop. In particular, the inner loop will continue, meaning num will get printed for every i that doesn't divide num evenly.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You are expecting that if any number below a number does not gets divisible by that number then print it

or you are finding if there are any roots of a number

In the Second code you are passing code sequence to else case every time you are checking divisibility with a number. However as expected you have to print the number only after the number passes the if condition on all numbers below it.

Himanshu
  • 666
  • 1
  • 8
  • 18