2015-10-11 208 views
-1

所以我運行python 2.7,並且我一直試圖讓這個代碼顯示與輸入(cha)相對應的數字(chamod),但是它一直返回0.我怎樣才能得到它得到相應的輸出?它應該打印出2.Python函數總是返回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() 
+4

其實它是'或' – cdonts

+0

@cdonts謝謝! ||顯示爲無效語法。什麼|那麼呢? –

+0

'|'是*按位或*。請參閱[BitwiseOperators](https://wiki.python.org/moin/BitwiseOperators)。 – cdonts

回答

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

做了「按位還是」。輸出的每一位爲0,如果相應的 位x和y的值爲0,否則是1

BitwiseOperators

2

前面已經別人提到你應該使用or而不是|。但是你真的應該做的是使用合適的字典,而不是如果,易學:

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集以外)。

+0

如果需要,你可以爲什麼擴大後一個範圍測試的功能,使其行爲像其他 – holroy