Jump to content

Recommended Posts

Posted (edited)
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
Posted

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.

Posted

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.

 

Posted

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. 

Posted
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...

Posted
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.

Posted

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.

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...