【问题标题】:Python: How do I get this function to print?Python:如何让这个函数打印?
【发布时间】:2011-02-16 18:18:42
【问题描述】:
#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'

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    在 Python 3.x 中,input总是 返回一个字符串,而不应用用户输入的eval。 Python 2.x input 确实是 eval,但这很少是你想要的。如果你想要一个整数,使用int(input(...)),如果你想要一个浮点数(与实数不太一样,因为它只有有限的范围!),使用float(input)。 (你应该抓住ValueError 来处理输入不合适的情况;如果这是为了练习/教育,现在可以忽略错误处理。)

    【讨论】:

      【解决方案2】:

      这必须在我定义函数之后出现吗?

      是的。

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

      TypeError: 不支持的操作数类型 -: 'int' 和 'str'

      您有两个- 操作。这两者之一是intstr 数据的混合。

      让我们遍历每个操作数。

      1 - 整数

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

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

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

      您可能想要将input() 的结果转换为适当的浮点值。 float() 很适合这个。

      【讨论】:

        猜你喜欢
        • 2022-11-26
        • 2017-06-16
        • 2021-12-19
        • 2011-10-19
        • 2021-03-01
        • 2016-11-01
        • 2020-08-07
        • 1970-01-01
        • 2013-12-06
        相关资源
        最近更新 更多