-1

I have 2 defined functions in which both need to use a line from a text file that is found. However because they are two different functions i can't use "line" in the one which doesn't search the text file for that line. So i want to take the value of "line" which was found and assign it to a variable to use in the later functions but i get the error that "variable_Line" is not defined.

Section of first function:

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

Second function

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
AntsOfTheSky
  • 195
  • 2
  • 3
  • 17

1 Answers1

2

Make add_cart accept an argument:

def add_cart(variable_Line):

You can then call it like this:

add_cart(variable_Line) #second function defined below
Francisco
  • 10,918
  • 6
  • 34
  • 45
  • I see. Global works fine so is there an advantage to using this way? or a disadvantage for using global? – AntsOfTheSky Nov 10 '16 at 17:12
  • It makes code hard to follow, and makes the input of the function practically the whole program, while also making it non-testable. You can read more about it [here](http://wiki.c2.com/?GlobalVariablesAreBad). – Francisco Nov 10 '16 at 17:15