2011-10-07 89 views
1

這是由我的教授發佈並由學生修改的羣體遺傳學程序。Python 2.7:L + = branch_length導致NameError:name'L'未定義

基本上它應該用給定的樣本,總體和突變率(u)來模擬20次預期的突變數。然而,關鍵部分是總分支長度(L),它是各種較小分支長度(分支長度)的總和。然而,當我如下定義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" 

我只是失去了一些東西真的,真的很明顯?提前致謝。

回答

4

L += x將x添加到現有L中,但是您尚未初始化L.推測,您希望L = 0位於文件頂部的某個位置。

+0

工作就像一個魅力。我知道這很簡單。 謝謝! – user984748

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.