Splitting an if statement
Everyone here has done a good job explaining how to get it right. I just want to explain what you are doing wrong.
if i / 3 == True
Equivalent to:
if i / 3 == 1
Because True == 1. So you're basically checking if i when divisible by 3 is 1. Your code will actually print 3 4 5.
I think you would like to check if I am a multiple of 3. Like this:
if i % 3 == 0
You can of course use an if statement for this. Or you can use a list comprehension if
[x for x in range(20) if x % 3 == 0]
Towards the down vote, from the python documentation :
Boolean values are two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example, when used as an argument to an arithmetic operator), they behave like integers 0 and 1, respectively.
a source to share
The short answer is no. You cannot do assignments on if statements in python.
But I don't really understand what you are trying to do here. Your example code will only print out the numbers 3, 4, and 5, because every other value of i divided by 3 evaluates to something other than 1 (and therefore false).
If you want to divide everything in the list by 3, you need a map (lambda x: x / 3, range (20)). if you want decimal answers, map (lambda x: x / 3.0, range (20)). They will return a new list in which each item will be a number in the original list, separated by three.
While working on Project Euler, I discovered that " if not x % y
" is the cleanest way of representing "if x is a multiple of y". This is equivalent to " if x % y == 0
" as seen in other answers. I don't think there is a significant difference between the two; which one you use is just a matter of personal preference.
a source to share