Jump to content

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
Link to post
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 post
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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...