Python:如何打印此功能?

时间:2011-02-16 18:18:43

标签: python-3.x

#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'

2 个答案:

答案 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'

您有两个-操作。其中一个是intstr数据的混合。

让我们浏览每个操作数。

1 - int

p - input()的结果,因此是一个字符串

n - input()的结果,因此是字符串

x - input()的结果,因此是字符串

您可能想要将input()的结果转换为适当的浮点值。 float()适用于此。