2011-02-16 90 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()适用于此。