# Break statement code

## Recommended Posts

```for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')```

There are two issues here:

1. TabError: Incosistent use of tabs and spaces in indentation

2. More importantly I don't understand the logic behind this code that leads to this output:

Quote
```
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3```

Edited by Truman

##### Share on other sites

Hopefully you've learned that indentation in Python is significant, so what does the error message tell you?

What you're missing with that code is probably the modulus or mod operator, the % operator.  Look up the modulus operator to see details, but it returns the remainder after a division.  So, for example, 17 % 5 equals 2, because 2 is the remainder of the division (5 goes into 17 3 times, with 2 left over).  So the line with the mod operator is testing if the two numbers are equally divisible with no remainder.

##### Share on other sites

This is how my code actually looks like in notepad++. From some reason forum <> function doesn't paste code with the same indentation.

Regarding the understanding of the code I understand mod operator but my miscomprehension was due to relation between for and else. Mixed things, now it's clearer.

##### Share on other sites

The problem is likely that you're mixing tabs and spaces. Use either one or the other. Not all editors have the same size tabs which is why your indentation goes wrong when pasting it on the forum.

##### Share on other sites

That else should be lined up with the if, not the for.

##### Share on other sites
4 hours ago, justsomeguy said:

That else should be lined up with the if, not the for.

Actually, else is lined up with for in official python tutorial and when I change it to what you suggested nothing changes...

##### Share on other sites
8 hours ago, Ingolme said:

The problem is likely that you're mixing tabs and spaces. Use either one or the other. Not all editors have the same size tabs which is why your indentation goes wrong when pasting it on the forum.

Interesting note, will keep that in my mind. Error message points to line 5 - break.

##### Share on other sites

Apparently in python a for loop can have an else.  That doesn't make a ton of sense, but I guess there are niche cases where that might be useful.

##### Share on other sites

If you indent else to if, it ignores 2, and repeats the same prime number output during loop.

## Create an account

Register a new account