Python函数保持返回0

时间:2015-10-11 22:54:02

标签: python python-2.7

所以我正在运行python 2.7并且我一直试图让这段代码用输入(cha)显示相应的数字(chamod),但它一直返回0.如何让它获得相应的输出?它应该打印出来。

def charismamod(cha):
    chamod = 0
    if cha == 1:
        chamod = -5
    elif cha == 2 | cha == 3:
        chamod = -4
    elif cha == 4 | cha == 5:
        chamod = -3
    elif cha == 6 | cha == 7:
        chamod = -2
    elif cha == 8 | cha == 9:
        chamod = -1
    elif cha == 10 | cha == 11:
        chamod = 0
    elif cha == 12 | cha == 13:
        chamod = 1
    elif cha == 14 | cha == 15:
        chamod = 2
    elif cha == 16 | cha == 17:
        chamod = 3
    elif cha == 18 | cha == 19:
        chamod = 4
    elif cha == 20:
        chamod = 5
    return chamod
def barbarian():
    cha = 14
    bchamod = charismamod(cha)
    print bchamod
barbarian()

3 个答案:

答案 0 :(得分:2)

您必须使用or代替|

def charismamod(cha):
    chamod = 0
    if cha == 1:
        chamod = -5
    elif cha == 2 or cha == 3:
        chamod = -4
    elif cha == 4 or cha == 5:
        chamod = -3
    elif cha == 6 or cha == 7:
        chamod = -2
    elif cha == 8 or cha == 9:
        chamod = -1
    elif cha == 10 or cha == 11:
        chamod = 0
    elif cha == 12 or cha == 13:
        chamod = 1
    elif cha == 14 or cha == 15:
        chamod = 2
    elif cha == 16 or cha == 17:
        chamod = 3
    elif cha == 18 or cha == 19:
        chamod = 4
    elif cha == 20:
        chamod = 5
    return chamod
def barbarian():
    cha = 14
    bchamod = charismamod(cha)
    print bchamod
barbarian()

|是一个按位运算符。您必须使用or||

  

x | ÿ

     

是"按位还是"。如果相应,则输出的每个位都为0   y的x和y的位是0,否则它是1。

BitwiseOperators

答案 1 :(得分:2)

正如其他人提到的那样,您应该使用or代替|。但是你应该做的是使用一个合适的字典而不是if-ology:

mapping = {
    1: -5,
    2: -4,
    3: -4,
    4: -3,
    5: -3,
    6: -2,
    7: -2,
    8: -1,
    9: -1,
    10: 0,
    11: 0,
    12: 1,
    13: 1,
    14: 2,
    15: 2,
    16: 3,
    17: 3,
    18: 4,
    19: 4,
    20: 5,
}

def charismamod(cha):
    return mapping.get(cha, 0)

这使得以后更容易阅读和更改。

你也可以玩数学:

def charismamod(cha):
    return (cha / 2) - 5

它为您提供了最紧凑和易于理解的功能(具有不同的功能,因为它对1, ..., 20集之外的任何内容的工作方式不同。)

答案 2 :(得分:0)

使用or

你所做的是“按位或”,它以与你想要做的不同的方式工作。 您可以在此处阅读快速摘要:http://www.tutorialspoint.com/python/bitwise_operators_example.htm