2010-03-26 81 views
0

我可以在終端下面的代碼鍵入,和它的工作原理:Python 3中與範圍功能

for i in range(5): 
    print(i) 

它將打印:

0 
1 
2 
3 
4 

如預期。不過,我試着寫一個腳本,做了類似的事情:

print(current_chunk.data) 
read_chunk(file, current_chunk) 
numVerts, numFaces, numEdges = current_chunk.data 
print(current_chunk.data) 
print(numVerts) 

for vertex in range(numVerts): 
    print("Hello World") 

current_chunk.data從以下方法獲得:

def read_chunk(file, chunk): 
    line = file.readline() 
    while line.startswith('#'): 
     line = file.readline() 
    chunk.data = line.split() 

這個輸出是:

['OFF'] 
['490', '518', '0'] 
490 
Traceback (most recent call last): 
    File "/home/leif/src/install/linux2/.blender/scripts/io/import_scene_off.py", line 88, in execute 
    load_off(self.properties.path, context) 
    File "/home/leif/src/install/linux2/.blender/scripts/io/import_scene_off.py", line 68, in load_off 
    for vertex in range(numVerts): 
TypeError: 'str' object cannot be interpreted as an integer 

那麼,爲什麼它不是吐出Hello World 490次?或者490被認爲是一個字符串?

我開這樣的文件:

def load_off(filename, context): 
    file = open(filename, 'r') 

回答

2

'490'是一個字符串。嘗試int('490')

0

感嘆,沒關係,它確實通過評估爲一個字符串。將for循環更改爲

for vertex in range(int(numVerts)): 
    print("Hello World") 

修復了這個問題。