2016-11-10 78 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)。 –

相关问题