2011-02-16 93 views
0
#integers to be input 
n = input('Enter \"n\" trials') 
x = input('Enter \"x\" number of succeses') 
p = input('Enter the probability \"p\" of success on a single trial') 

#Probability Distribution function 
def probDist(n, x, p): 
    q = (1-p)**(n-x) 
    numerator = math.factorial(n); 
    denominator = math.factorial(x)* math.factorial(n-x); 
    C = numerator/denominator; 
    answer = C*p**x*q; 

    return answer 

# Does this have to come after I define the function? Or does this matter in Python 
# Also this part just doesn't work. 
dist = probDist(n, x, p); 
print(dist); 

這是我運行後輸入的錯誤,我輸入了所有的值。Python:如何獲得打印此功能?

Traceback (most recent call last): 
    line 17, in <module> 
    dist = probDist(n, x, p); 
    line 9, in probDist 
    q = (1-p)**(n-x) 
TypeError: unsupported operand type(s) for -: 'int' and 'str' 

回答

5

在Python 3.x中,input總是返回字符串,而不應用eval的所述用戶輸入。 Python 2.x input does eval,但這很少是你想要的。如果你想要一個整數,使用int(input(...)),如果你想要一個浮點數(與實數不完全相同,因爲它只有有限的範圍!),請使用float(input)。 (你應該propably趕上ValueError處理情況輸入不是appropiate;如果這是鍛鍊/教育,這是propably還好現在將要離開的錯誤處理出來)

2

Does this have to come after I define the function?

是。

q = (1-p)**(n-x)

TypeError: unsupported operand type(s) for -: 'int' and 'str'

您有兩個-操作。其中之一是intstr數據的混合。

讓我們來看看每個操作數。

1 - INT

p - 的input()結果,並因此一個字符串

N - 的input()結果,並因此一個字符串

X

- 結果的input(),因此一個字符串

您可能想要將input()的結果轉換爲適當的浮點值。 float()適用於此。