模数问题

Modulus problems

**我在使用模数进行简单的双赢游戏时遇到问题。 **无论是偶数还是奇数,无论如何,return 是 "Odd you win" 或 "Even you win" 即使玩家 + cpu = 3 % 2 = 1 在函数中(偶数)我得到 "Even you win."

的 return
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()

输出

**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**

您需要使用括号:

if (player + cpu) % 2 != 0:

你可以通过一个简单的例子看出区别:

In [10]:  5 + 5 % 2
Out[10]: 6

In [11]:  (5 + 5) % 2
Out[11]: 0

%+ 具有更高的 precedence,因此首先执行模运算,然后将 5 添加到结果中。

In [12]:  5 % 2 
Out[12]: 1

In [13]:  5 % 2  + 5
Out[13]: 6

modulo 仅适用于 cpu 变量。

使用(player + cpu) % 2来计算总和。

>>> player = 2
>>> cpu = 1
>>> player + cpu % 2
3
>>> (player + cpu) % 2
1

% 使用 */ 求值,因此它在 operations 中先于 +(计算之前)。