#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);
这是我跑完后输入的所有错误。
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'
答案 0 :(得分:5)
在Python 3.x中,input
始终返回一个字符串,而不应用eval
用户输入。 Python 2.x input
执行eval
,但这很少是你想要的。如果你想要一个整数,使用int(input(...))
如果你想要一个浮点数(与实数不完全相同,因为它只有有限的范围!),使用float(input)
。 (你应该合适地抓住ValueError
来处理输入不合适的情况;如果这是用于锻炼/教育,那么现在可以暂时停止错误处理。)
答案 1 :(得分:2)
在定义函数后,是否必须这样做?
是
q =(1-p)**(n-x)
TypeError:不支持的操作数类型 - :'int'和'str'
您有两个-
操作。其中一个是int
和str
数据的混合。
让我们浏览每个操作数。
1 - int
p - input()
的结果,因此是一个字符串
n - input()
的结果,因此是字符串
x - input()
的结果,因此是字符串
您可能想要将input()
的结果转换为适当的浮点值。 float()
适用于此。