Home > Back-end >  How do I change the value of a global variable across multiple functions
How do I change the value of a global variable across multiple functions

Time:06-03

I'm altering the value of a global variable in my code but it reverts back to the original value each time. How can I fix this?

global a
a = 1

def F1():
  a = 2

def F2():
  print(a)

F1()
F2()

I get an output of 1 but I'm wanting it to be 2 as per the change in F1.

CodePudding user response:

Check out Python Programming FAQ for the rules for local and global variables.

a = 1

def F1():
  global a
  a = 2

def F2():
  print(a)

F1()
F2()

You are trying to modify the value of global a in F1, so you need to declare a as global there.

  • Related