-2

Is it possible to change a variable without making a new one in python?

here is an example:

x = True


def reverseX():
  x = not x


print(x)
reverseX()
print(x)

now this will return an error because it thinks that I was making a new x in the reverseX thing is there a way for me to use the x that's at the top of the script in the reverseX thing?

btw, I know that I can use the return or just not use the reverseX thing, but sometimes you just need to use a def also, I know that I can pass the x variable through the call but is there another way?

tripleee
  • 175,061
  • 34
  • 275
  • 318
ZiyadCodes
  • 379
  • 3
  • 10

1 Answers1

1

In your example you could do it by making x a global variable:

global x
x = True

def reverseX():
    global x
    x = not x

print(x)
reverseX()
print(x)

While this does work, I do not recommend it. As using global variables in more complex projects can lead to some problems, explained in this question. A much better way of doing it would be:

x = True

def reverseBool(var):
    return not var

print(x)
x = reverseBool(x)
print(x)
Marko Borković
  • 1,884
  • 1
  • 7
  • 22