In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.
a = range(20)
for i in a:
if i / 3 == True:
print i
In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.
a = range(20)
for i in a:
if i / 3 == True:
print i
Yes, but.
Please, please, please. Never say if some expression == True
. It's redundant and causes many people to wonder what you're thinking.
More importantly.
i/3
is the quotient.
i%3
is the remainder. If i is a multiple of 3, i%3 == 0
.
Hmm seems you want a weird thing - you divide i by 3 and check if it is equal to 1. As 4 == True => False.
Short answer: no. You cannot make assignments in if statements in python.
But really, I don't understand what you are trying to do here. Your sample 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 a list by 3, you want map(lambda x: x / 3, range(20)). if you want decimal answers, map(lambda x : x / 3.0, range(20)). These will return a new list where each element is a the number in the original list divided by three.
At the command prompt:
>>> [i for i in range(20) if i%3 == 0]
>>> [0, 3, 6, 9, 12, 15, 18]
OR
>>> a = [i for i in range(20) if i%3 == 0]
>>> print a
[0, 3, 6, 9, 12, 15, 18]
>>>
While working on Project Euler myself, I found "if not x % y
" to be the cleanest way to represent "if x is a multiple of y". This is equivalent to "if x % y == 0
", seen in other answers. I don't believe there is a significant difference between the two; which you use is simply a matter of personal preference.
Everyone here has done a good job explaining how to do it right. I just want to explain what you are doing wrong.
if i / 3 == True
Is equivalent to:
if i / 3 == 1
Because True == 1. So you are basicly checking if i when divided by 3 equals 1. Your code will actually print 3 4 5.
I think what you wanted to do is to check if i is a multiple of 3. Like this:
if i % 3 == 0
You can of course use an if statement to do it. Or you can use list comprehension with if
[x for x in range(20) if x % 3 == 0]
To those how are down voting this, from python documentation:
Boolean values are the 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 the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.