I just started trying to learn Python. I was following some tutorials that showed a simple way for finding prime numbers. I decided to modify it a bit to just try and output whether numbers in a set were divisible by 3. This is what I came up with.
for n in range(3, 13):
for x in range(3, n):
if n % x >= 1:
print(n, 'Is not divisible by 3')
break
else:
print(n, 'is divisible by 3')
Unfortunately, this is only showing 3 as being divisible by 3, and 4-12 not being divisible by 3. Can anyone explain where I'm going wrong?
why do you have a break there?
I copied straight from the Idle, so it isn't preserving the indentation in the post, I guess.
>>55966048
Because the function loops and gives the outputs for each number several times without it
it's in python
While I'm still curious what I did wrong, there was a much simpler way of doing it, it seems.
for n in range(3, 13):
if n % 3 >= 1:
print(n, 'Is not divisible by 3')
continue
print(n, 'is divisible by 3')
use [ code ] [ /code ] tags (remove the spaces) to preserve whitepsace.
i'm not going to bother trying to understand your thought-process in the code you've written but the proper way to tell if something is divisible by 3 is to check that x % 3 == 0
a cool way of selecting all of the elements in an iterable that are divisible by 3 is with list comprehensionsmy_thing = range(3, 13)
[n for n in my_thing if n % 3 == 0]
I think I found your example, and if you followed that examples indentation then your else is on the for loop and not the if statement. In that case it wouldn't catch anything higher than 3 because your weren't just checking x, you were checking from 3 to x and 4 will break that for loop for each of those iterations
>>55966026
look at why it shows 6 as not being divisible by 3. when x = 4 in the inner loop, 6 divided by 4 leaves a remainder of 2, which is greater than 1. so, '6 is not divisible by 3' will be printed.
>>55966176
This is still to complicated. Without getting super pythonic and flying into generators or comprehensions you'd be better off using an else there rather than a continue.
>>55966176
use n%3 == 0 instead of n%3 >= 1 to check if n is divisible by 3. the modulo operation in python can return a negative number and is not consistent with euclidean division.
>>55966230
Well, my thought process was a bit off, since I started with code from for prime numbers. Initially, I was having it check for remainder being equivalent to 0, but it still wasn't coming out right. I suppose I was ultimately just making things way too complicated.