2016-11-10 80 views
-1

我有兩個定義的函數,其中都需要使用找到的文本文件中的一行。然而,因爲它們是兩種不同的功能,我不能在不搜索該行的文本文件的那一行中使用「行」。所以我想要找到找到的「行」的值,並將其分配給一個變量,以便在後面的函數中使用,但是我得到「variable_Line」未定義的錯誤。將.txt文件中的行分配給一個變量python供以後使用

科第一功能:

while (len(code) == 8): 
    with open('GTIN Products.txt', 'r') as search: 
     for line in search: 
      line = line.rstrip('\n') 
      if code in line: 
       variable_Line = line #This is where i try to assign contents to a variable 

       print("Your search found this result: "+line) #this prints the content of line 

       add_cart() #second function defined below 

二級功能

def add_cart(): 
    add_cart = "" 
    while add_cart not in ("y", "n"): 
     add_cart = input("Would you like to add this item to your cart? ") 
     if add_cart == "y": 
      receipt_list.append(variable_Line) #try to use the variable here but get an error 

     if add_cart == "n": 
      break 
+0

爲了便於閱讀,我強烈建議您不要在名爲'add_card'的函數內創建一個名爲'add_card'的局部變量。 – Jeff

+0

我看到你從哪裏來,謝謝你的提示! :) – AntsOfTheSky

回答

2

add_cart接受參數:

def add_cart(variable_Line): 

然後你可以這樣調用:

add_cart(variable_Line) #second function defined below 
+0

我明白了。全球工作正常,所以使用這種方式有什麼優勢?或使用全球的劣勢? – AntsOfTheSky

+0

它使代碼難以遵循,並使得函數的輸入實際上成爲整個程序的一部分,同時也使其不可測試。你可以閱讀更多關於它[這裏](http://wiki.c2.com/?GlobalVariablesAreBad)。 –

相關問題