我是Python新手(這是我的第二語言),所以希望我的問題可以幫助別人也在類似的事情上掙扎。在For循環中的名稱未定義錯誤?
僅供參考,我使用Netbeans IDE 6.9.1並運行Python 2.7.3。有點背景故事,我正在研究論文的交通問題,我需要生成城市(節點)和道路(弧)的網絡。我在下面的代碼中做的是生成一個字符串,我將它傳遞給一個打開的(文件,'w')操作,在這裏我將隨機生成的數據寫入文本文件。
例如:FNodes = '\ DijkstraShortestPath \數據\ 100Nodes \ Node5.txt'
總是收到一個 「名 'Fnodes' 沒有定義」 錯誤,當我下面運行該代碼。
我花了數小時試圖弄清楚這一點;不應該這樣定義?畢竟,我寫過「FNodes = bla bla bla」。
我試着將它從循環中取出,但由於它們在FNodes字符串中使用,導致與'item'和'replications'相同的錯誤。這是有道理的,因爲它們是在for循環中定義的。
如果你能幫助一個新人理解這個語法錯誤,那會很棒。
感謝您的幫助。
R = 10 #Number of replications (trials)
NumNodes = [50,100,150] #Number of nodes (cities). Also the names of 3 folders.
for item in NumNodes: #Cycle through 50, 100, 150 nodes for folder path XXXNodes
for replications in range(R): #Cycle through fileR.txt by replication number
fNodes = "\\DijkstraShortestPath\\Data\\" + str(item) + "Nodes\\Node" \
+ str(replications + 1) + ".txt"
print FNodes #This is a debugging step for me so I can see what's happening
#Write to files and stuff...
我想知道爲什麼你不顯示引發異常的實際代碼。 「打開」電話在哪裏?請展開您的代碼段。順便說一下,如果你的路徑是相對的,它可能不應該以斜槓開始。 – 2013-03-12 19:29:55
我注意到了錯誤 - 當我實際定義了fNodes時,我試圖引用FNodes。大寫錯誤。 「相對」路徑是什麼意思? – Chris 2013-03-14 04:05:00
相對路徑顯示相對於當前目錄的文件位置。絕對路徑從文件系統樹的根開始。 – 2013-03-14 07:14:49