模数问题

时间:2016-10-17 22:41:34

标签: python math modulus

**我在使用模数进行简单的平均和赔率游戏时遇到了问题。 **无论是偶数还是奇数,无论是什么,回报都是"奇怪的是你赢了"或者"即使你赢了"即使玩家+ cpu = 3%2 = 1在函数中(偶数)我得到了回报#34;即使你赢了。"

Function

输出

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

2 个答案:

答案 0 :(得分:2)

你需要使用parens:

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

您可以通过一个简单的示例看到差异:

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

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

%的{​​{3}}高于+,因此首先执行模数,然后将5添加到结果中。

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

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

答案 1 :(得分:1)

模数仅适用于cpu变量。

使用(player + cpu) % 2将其应用于总和。

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

%使用*/进行评估,因此它位于operations +之前(之前计算)。