Skip to main content
 首页 » 编程设计

python之python错误: unsupported operand type(s) for *: 'int' and 'NoneType'

2025年05月04日87虾米姐

我正在提供我的输入文件:

2 1   

我写了一段代码来查找概率(特定于我的工作):

def fact(x): 
    f=1 
    if x > 0: 
        for i in range(1,x + 1): 
            f = f*i 
        return f 
 
 
def allele(s): 
    n,k=[int(i) for i in s.split()] 
    summ=0 
    for i in range(n,((2**k)+1)): 
            if i < (2**k +1): 
                probability = (fact(2**k)/(fact(i)*fact((2**k)-i)))*(0.25**i)*(0.75**((2**k)-i)) 
                summ=summ+probability 
    print summ 
 
allele(open('D:\python\input.txt', 'r').read())   

我在计算概率的那一行出现错误:

unsupported operand type(s) for *: 'int' and 'NoneType'  

我不知道怎么解决。

请您参考如下方法:

您的 fact 函数为 0 而不是 1 返回 None 因为您缩进了 return f 一个额外的级别。

def fact(x): 
    f = 1 
    if x > 0: 
        for i in range(1, x + 1): 
            f *= i 
    return f 

真的,你应该只使用 math.factorial为此。

from math import factorial as fact