kloe - 1 month ago 4
Python Question

# what is the difference between these two programmes

``````b=input("Enter number : ")
for n in range(2, b+1):
for x in range(2, n):
if n % x == 0:
break
else:
print n
``````

This program prints prime numbers up to n
Out put is

Enter number : 10

2

3

5

7

and

``````b=input("Enter number : ")
for n in range(2, b+1):
for x in range(2, n):
if n % x == 0:
break
else:
print n
``````

out put is

Enter number : 10

3

5

5

5

7

7

7

7

7

9

``````b=input("Enter number : ")
for n in range(2, b+1):
for x in range(2, n):
if n % x == 0:
break
else:
print n
``````

prints out `n` if `n % x` has no remainder and only the first correct value since it breaks out.

``````b=input("Enter number : ")
for n in range(2, b+1):
for x in range(2, n):
if n % x == 0:
break
else:
print n
``````

prints out every `n` that has a non zero remainder until the first zero remainder appears.

More on how `for else` works:

`for else` will run the for loop and then run the else right after the for loop finishes. In your case the for loop ends at a certain point and then prints the resulting value where it ended at.

``````for x in range(10):
print x
else:
print "hello world"
``````

Take this for example. It prints out :

``````0
1
2
3
4
5
6
7
8
9
hello world
``````

Why is this useful? Well your program gives a very nice example on why it is. We want to exit the for loop for a certain condition that passed, and then do something after we've found that condition (if we've found the passing condition else we just run it anyways). So if condition is met in for loop run this, or run this at the end of the for loop always.

Back to your question, basically the first one finds the factors of the number given, and the second one finds the non factors of the number given.