3

I want to create a python program where I can modify the values in a program and use the modified values in another program. Here's an example:

vars.py

a = 20
b = 30
x = 20+30

func.py

import vars
def changevalues():
    vars.a = 40
    vars.b = 50

main.py

import vars
import func

func.changevalues()
print(vars.x)

When I run main.py, the output I want is 90, but it adds up 20 and 30 and the output is 50.

4
  • 3
    Your code is printing vars.x which you set to 20+30 in vars.py. It doesn't matter what you set a and b to when x is still set to 50. Also worth mentioning that you are simply calling print on vars.x so whatever that is set to is what's going to print. The function isn't affecting anything. Commented Oct 18, 2022 at 4:30
  • ...note that what @Jackie explains would be true even if the third line of your "vars.py" file were x = a + b. x is set when the file is imported. So later changes to a and/or b would not change the value of x in that case either. Commented Oct 18, 2022 at 4:33
  • @CryptoFool, is there any way that the value of x will also be changed along with a and b? Commented Oct 18, 2022 at 5:26
  • @BitanSarkar You declared x as an int, which is immutable. So the only way to change it is by assigning it to another value. If you want it to track changes in a and b, then x needs to be a callable (a function, for example), a class property, or a mutable type, like a list, for example. Commented Oct 18, 2022 at 6:05

1 Answer 1

1

The only change you need to make to your code is to change the existing variable x from within your function. So, for example, add just one line to changevalues():

def changevalues():
    vars.a = 40
    vars.b = 50
    vars.x = vars.a + vars.b

Then run main.py and your result will be:

90
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.