Home > Net >  Update value of a variable in a module
Update value of a variable in a module

Time:11-27

I have two files main.py and val.py. A value is taken from val.py in the main file and then I want to update the variable in the original file. Then use that value further in the calculations. Each time when I call the function I want to get the updated value rather than the initial value. But I am only getting the initial value here.

val.py

num = 0

#update the original value
def update(num):
  num  =1
  return 

#get the current 'num' value
def current():
  return num

Main.py

import val

val.update(val.current())

print(val.current())

The global variable is not getting updated. I can't seem to figure out the correct issue here. I am passing the values as well in the functions as arguments. It would be really helpful if someone could even give a hint.

CodePudding user response:

In update(), you've shadowed the module's num variable with a local variable that's also called num. If you get rid of it and use the global keyword, you can modify the module's num value.

num = 0

def update():
    global num
    num  = 1
  • Related