Python 2.7: L += branch_length导致NameError: name 'L'未定义

1 投票
2 回答
599 浏览
提问于 2025-04-17 03:54

这是一个由我的教授发的种群遗传学程序,学生们对它进行了修改。

简单来说,这个程序是用来模拟在给定的样本、种群和突变率(u)下,预计会发生的突变次数,总共模拟二十次。不过,有一个关键的部分是总分支长度(L),它是各种较小分支长度(branch_length)的总和。但是,当我下面这样定义L的时候,程序总是报错:

  L += branch_length  
NameError: name 'L' is not defined

我不太确定哪里出了问题,因为tree_depth的定义方式是一样的,而且运行得很好。

这是完整的代码:

from random import expovariate
from pgen import poidev
K = 77       # sample size (number of gene copies)
twoN = 5000  # population size
u = .001

tree_depth = 0.0 # age of last common ancestor in generations

# Each pass through loop deals with one coalescent interval.

for A in range(20):
    while K > 1:
        h = K*(K-1)/(2.0*twoN) # hazard of a coalescent event
        t = expovariate(h)       # time until next coalescent event
        tree_depth += t
        branch_length = t*K
        K -= 1
        L += branch_length
    S = poidev(u*L)
    print "Simulation:", A+1, "Total Mutations:", S
print "Total tree depth (L):", L, "generations"

我是不是漏掉了什么非常明显的东西?提前谢谢你们。

2 个回答

1

你需要在执行 L += x 之前先定义 L = 0

一般来说,在修改一个变量之前,你需要先定义它。对于赋值来说,没问题,因为Python会自动推断变量的类型。

以下是一些例子:

>>> a += 0 #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = 5 #Valid
>>> a += 0 #Now it's valid, because a is defined.
>>> 
>>> my_list.append(5) #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'my_list' is not defined
>>> my_list = [] 
>>> my_list.append(5) #Now valid
>>> my_list
[5]
>>>
>>> my_list2 = [1, 2, 3, 4] #Valid, because it's an assignment.
4

L += x 是把 x 加到已经存在的 L 上,但你并没有给 L 赋初值。一般来说,你应该在文件的开头某个地方写 L = 0 来初始化 L。

撰写回答