Jump to content

Break statement code


Truman

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
Link to comment
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.

Link to comment
Share on other sites

image.thumb.png.ca8283a86a8539bca9d9e85f8eb36d7c.png

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.

 

Link to comment
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. 

Link to comment
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...

Link to comment
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.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...