0

I seem to have to define this global variable in my code twice to remove errors which cant be right. The code just asks to input an object and adds it to a new list. If the user wants to skip this step he can let the new list = an old listed created earlier in the code.

I am must have the syntax wrong somewhere but cant figure out where. My code is below, grateful for any help thanks.

global new_object_list


def get_input_object(prompt):

        global new_object_list
    # new_object_list is defined without usage
        new_object_list = []

        while True:
            chosen_object = input(prompt)
            if chosen_object in my_list:
                new_object_list.append(chosen_object)
                # allows user to break out of loop on carriage return
            if chosen_object == '\r':
                break
                # allows user to let new list = copy of old list then exit input
            if chosen_object == 'all':
                new_object_list = my_list.copy()
                break
                # return outside of function
        return chosen_object


print(get_input_object('Enter entities separated by space'))
print(new_object_list)
kederrac
  • 16,819
  • 6
  • 32
  • 55
Sid
  • 153
  • 3
  • 15
  • On line `if chosen_object in my_list:` (and following lines) `my_list` is not defined. Did you mean new_object_list? – DarrylG Apr 09 '20 at 14:41
  • Does this answer your question? [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – Josh Karpel Apr 09 '20 at 14:46
  • Sorry - my_list has been defined earlier in the code and contains a list of items – Sid Apr 09 '20 at 15:10
  • Josh, but still was having problems also I using 3.7 , so not sure about the differences – Sid Apr 09 '20 at 15:14
  • `global new_object_list` doesn't declare or define a variable; it simply says that any use of the name `new_object_list` inside the function refers to the object by the same name in the global scope. – chepner Apr 09 '20 at 15:49

1 Answers1

0

Define the list in the global scope, so that your function doesn't have to decide if it needs to create the list first.

new_object_list = []


def get_input_object(prompt):

        global new_object_list

        while True:
            chosen_object = input(prompt)
            if chosen_object in my_list:
                new_object_list.append(chosen_object)
                # allows user to break out of loop on carriage return
            if chosen_object == '\r':
                break
                # allows user to let new list = copy of old list then exit input
            if chosen_object == 'all':
                new_object_list = my_list.copy()
                break
                # return outside of function
        return chosen_object
chepner
  • 497,756
  • 71
  • 530
  • 681