Reputation: 13
**I'm having problems using modulus for a simple evens and odds game. **Whether for even or odd no matter what, the return is "Odd you win" or "Even you win" even when the player + cpu = 3 % 2 = 1 in function (even) I get a return of "Even you win."
import random
even_odds = list(range(0,2))
play = random.choice(even_odds)
def selection():
which = input('Select O for odds and E for even: ').lower()
if which == 'o':
odds()
elif which == 'e':
evens()
def odds():
even_odds
cpu = random.choice(even_odds)
print("YOU CHOSE ODD")
player = int(input("Choose a number between 0 and 2: "))
print('cpu chose',cpu)
print("You're choice plus the cpu's choice equals",player + cpu)
print(" /n ...", player + cpu % 2 )
if player + cpu % 2 != 0:
print('Odd you win\n')
selection()
else:
print('Even you lose!\n')
selection()
def evens():
even_odds
cpu = random.choice(even_odds)
print("YOU CHOSE EVEN")
player = int(input("Choose number between 0 and 2: "))
print('cpu chose',cpu)
print("You're choice plus the cpu's choice equals",player + cpu)
if player + cpu % 2 == 0:
print('Even you win! \n')
selection()
else:
print('Odd you lose! \n')
selection()
Output
**Select O for odds and E for even: o
YOU CHOSE ODD
Choose a number between 0 and 2: 2
cpu chose 0
You're choice plus the cpu's choice equals 2
... 2
Odd you win**
Upvotes: 0
Views: 112
Reputation: 16224
The modulo applies only for the cpu
variable.
Use (player + cpu) % 2
to apply it for the sum.
>>> player = 2
>>> cpu = 1
>>> player + cpu % 2
3
>>> (player + cpu) % 2
1
%
evaluates with *
and /
, so it precedes +
in operations (calculates before).
Upvotes: 1
Reputation: 180522
You need to use parens:
if (player + cpu) % 2 != 0:
You can see the difference with a simple example:
In [10]: 5 + 5 % 2
Out[10]: 6
In [11]: (5 + 5) % 2
Out[11]: 0
%
has a higher precedence than +
so the modulo is performed first, then 5 is added to the result.
In [12]: 5 % 2
Out[12]: 1
In [13]: 5 % 2 + 5
Out[13]: 6
Upvotes: 2