Splitting an if statement

In Python, if I had a range and I wanted to iterate over it and divide each number by another number, can I do it in an if statement.

a = range(20)
for i in a:
   if i / 3 == True:
      print i

      

0


a source to share


6 answers


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.

+2


a source


Yes, but.

Please, please, please. Never tell if some expression == True

. This is overkill and leaves many people wondering what you are thinking.

More importantly.



i/3

is private.

i%3

is the remainder. If I have multiple of 3 i%3 == 0

.

+7


a source


On the command line:

>>> [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]
>>>

      

+2


a source


Hmm, it seems you want a weird thing - you divide me by 3 and check if it equals 1. Like 4 == True => False.

0


a source


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.

0


a source


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.

0


a source







All Articles