-2

I'm trying to print numbers within a method in a class. There is a function get_numbers() responsible to generate numbers should always be outside of the class.

If I try like this, the get_result method keep on printing numbers:

import time
import random

def get_numbers():
    numbers = [i for i in range(10)]
    return numbers

numbers = get_numbers()
random.shuffle(numbers)

class NumChecker:

    def get_result(self):
        print(numbers.pop())
        time.sleep(2)

parse = NumChecker()
while True:
    parse.get_result()

However, when I try like the following, the script throws this error UnboundLocalError: local variable 'numbers' referenced before assignment pointing at if len(numbers)<=5 whereas I didn't get any error when I used this print(numbers.pop()) above:

    def get_result(self):
        if len(numbers)<=5:
            print("updating numbers")
            numbers = get_numbers()
            random.shuffle(numbers)
        else:
            print(numbers.pop())
            time.sleep(2)

Is it necessary to use global numbers within get_result() to avoid such error?

rdas
  • 20,604
  • 6
  • 33
  • 46
asmitu
  • 175
  • 11
  • This happens because at some point in the method you assign to `numbers` so it is unclear if you want to use the global or local version. The first access in the if statement uses the global but within the first clause it gets assigned to, so it becomes a local. Thus, an error occurs – N Chauhan Jun 09 '20 at 07:53

1 Answers1

1

In short - yes. The following works:

def get_result(self):
    global numbers
    if len(numbers)<=5:
        print("updating numbers")
        numbers = get_numbers()
        random.shuffle(numbers)
    else:
        print(numbers.pop())
        time.sleep(2)

Since you're assigning a value to numbers in get_result, it 'thinks' it's a local variable, and produces the error you report.

Roy2012
  • 11,755
  • 2
  • 22
  • 35