Search code examples
pythonvariablesscope

Get all values of local variable value outside of function


      soup = BeautifulSoup(filehandle, "html.parser")
      soup = soup.find('ul', class_='listing')
      thdr = soup.find('div', class_='heading')

      if (chk == "n"):
         
      while (thdr != None):
      for thdr in thdr:
         global prod      
         temp = thdr.string
         prod = thdr.string
         print prod

I need to print the value of prod ouside of this function and loop. This variable prod has multiple values but I am getting only the last value when I print this outside of function even after marking it as global.


Solution

  • I'm not quite sure what the code in your question is doing, so I'll use the sample code below to answer your question.

    Solution

    Using yield keyword. It is used to create a generator function. A type of function that is memory efficient and can be used like an iterator object.

    Sample Code

    def foo(num):
        while num < 10:
            num += 1
            yield num
    
    for n in foo(0):
        print(n)
    

    Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10