Python - Variable problem

Asked

Viewed 107 times

0

I don’t know where I’m going wrong, but I wrote the following line of code:

#variaveis globais
fcfs = False
#commands

def fcfscheck():

    fcfs = not fcfs

Supposedly this function should alternate the value of fcfs between true and false every time it was called, but I’m getting an error:

Unresolved Reference 'fcfs'

  • https://answall.com/q/250362/5878

  • This is a name conflict, you have a local variable with the same name as a variable declared in the global scope, change the name of your variable and you will no longer have conflict.

3 answers

1

This is a name conflict, you have a local variable with the same name as a variable declared in the global scope, change the name of one of its variables and no more conflict.

And as the local variable takes precedence, soon it will not be possible to obtain the value of fcfs because it does not yet exist in the local scope of its function, however, if I change the name of its local variable there will be no conflict, see:

#variaveis globais
fcfs = False
#commands

def fcfscheck():
  outroNome = not fcfs

And if you want to reference your global variable without changing the name, do what was suggested in the other answers global fcfs, but try to make it easier for those who read your code.

0

Try this way:

def fcfscheck():
   global fcfs
   fcfs = not fcfs

It is necessary to indicate in the function that you want to modify the global variable.

0

You need to use the global in the variable to use itself within a function

#variaveis globais
fcfs = False
#commands

def fcfscheck():
    global fcfs
    fcfs = not fcfs

A cool tip, I don’t know which IDE you use, in my case I use Vscode with the Pylint extension, it indicates these errors easily

inserir a descrição da imagem aqui

  • In this specific case, you are right, but in python you can use the more restricted scope variables defined in the wider scope without having to declare that they are global. The problem is that the question code uses the same variable name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.