-1

I'm trying to index a list using a variable and "test" should check if indexer is out of date and then updating it through "maybe", I've tried using "global" but I don't think I understand it fully and I've also tried to put "indexer = indexer" but that also won't work. Any solutions?

indexer = 0
list = ["no", "yes"]
maybe = 1
def test():
  if indexer << maybe:
    indexer = maybe
    print("boooo")
test()
  • 1
    do not use `list` as a variable name; it overwrites the built-in list function. Also is there a reason you do not want to pass your list, indexer and maybe as params of the function? – It_is_Chris Nov 02 '22 at 15:05

2 Answers2

0

<< is not used for comparing values. see explanation.

What you need is:

if indexer < maybe:
    indexer = maybe
Flow
  • 551
  • 1
  • 3
  • 9
0

Globals in general are a bad idea since they produce implicit assignations. Instead, is better to use return to explicitly update the values.

If you want the function to take arguments created outside it, you can input them as arguments, e.g.:

indexer = 0
maybe = 1
def test(indexer, threshold):
    if indexer < threshold:
        indexer = threshold
    return indexer  # outside, so it'll always return


indexer = test(indexer=indexer, threshold=maybe)
indexer  #1

If it really makes sense to you to think on indexer and maybe as defining the state of the program, and you prefer to modify them implicitly, you can still do

indexer = 0
maybe = 1
def test():
    global indexer, maybe
    if indexer < maybe:
        indexer = maybe

test()
indexer  # 1

A note on variables not defined in the local space

This is a simplified and corrected version of your program:

indexer = 0
maybe = 1
def test():
  if indexer < maybe:
    indexer = maybe

That produces local variable 'indexer' referenced before assignment.

However, if I make this change:

indexer = 0
maybe = 1
def test():
  if indexer < maybe:
    foo = maybe  # Change here!!!

there's no error!

that's because when Python finds variables inside the function declaration that were not declared in it's body (like foo in the example), it's going to look for them in an outer namespace (the global space in this case). In your code you were lucky enough that, because you declared indexer = maybe inside the body, the compiler assumed you wanted to use that declaration and not the one from the global and raised an error. Lucky enough... because this could be a source for many semantic errors. So, it's better to explicitly declare where the names are coming from instead of waiting for python to look for them in ways that may surprise us later when we want to change our program.

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15