psychopy.org | Reference | Downloads | Github

What does this command do: if i % 2 == 1:

I am trying to put one stimulus on an odd number of trials and another on an even number but not sure if the code is correct or what it means… Also can’t find what % (modulus) is/means/does…Please help. My code so far is:

for i in range(1,10): 
    if i % 2 == 1: 
        stimOn = 'blue'
        stimBlue.draw()
    if i % 2 == 2:
        stimOn = 'red'
        stimBlue.draw()

@Sally_Knowles,

i%2 == 1 # odd
i%2 == 0 # even

>>> for i in range(1,10):
...     print(i,i%2)
...
1 1
2 0
3 1
4 0
5 1
6 0
7 1
8 0
9 1
>>>

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7+ 0.34 .) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1].

Python expressions

Thank you! Ive changed the “if i % 2 == 2:” to “if i % 2 == 0” but not sure what the 2 represents now (i thought it referred to the the second stimuli…?) :exploding_head:

Well I don’t know your experiment, but even numbers are divisible by 2. That’s the definition. Odd numbers can then be defined as those numbers that are not even. Remember that in Python, things start at 0, not 1. If you have a list say lst=[‘a’,‘b’,‘c’], the first element is lst[0], not lst[1].

1 Like