0

When I try and use the code below, even when I run the set_list_index function it doesn't change the list_index variable. I.E. I pass it a 2 and list_index stays as a 0. I don't understand why it is failing to make this change, but it seems like it is failing to recognize the list_index variable because it is not within the function?

list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    list_index == num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()
Steve
  • 85
  • 7
  • 1
    Python? It's not tagged with a language yet. – MSalters Feb 08 '22 at 11:22
  • apologies, tagged with python now – Steve Feb 08 '22 at 11:24
  • `list_index = num`? – TitoOrt Feb 08 '22 at 11:29
  • yes I thought I would be able to pass set_list_index an integer using this, should I use "int" instead of "num"? – Steve Feb 08 '22 at 11:44
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Max Feb 08 '22 at 12:08
  • @MaxMiller I would have thought so but even when I add "global list index" as the first line of set_list_index it still doesn't change list_index when I pass it a number. Maybe the issue isn't with the variable? – Steve Feb 08 '22 at 12:17
  • 2
    it has to be `=` instead of `==` in `list_index = num`. And it needs `global list_index` in `set_list_index` – furas Feb 08 '22 at 12:18
  • Thanks @furas it turns out that in conjunction with the global variables thing was the solution – Steve Feb 08 '22 at 12:19
  • Why not *return* a value and use: `list_index = set_list_index(num)`? Using global variables is frequently a sign of poor design. – John Coleman Feb 08 '22 at 12:36

1 Answers1

0

Step 1 to fix: define the list_index as "global" step 2: remove unneccessary second =

resulting fixed code:

list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    global list_index
    list_index = num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()
Steve
  • 85
  • 7