简体   繁体   中英

Updating a variable from a function in a different file in python

I am trying to keep the value of a variable between files on a python script. The end goal is to separate functions from an algorithm.

The function is very simple - I have saved it in a file called test:

def tests(x):
    global y
    x=10

    y=x
    return y

Then the algorithm part is again simple - saved in a different file, called test1:

import test as t
y=0
t.tests(y)
print("new value is "+str(y))

However, the value does not seem to be updated to 10 - it keeps its initial value of 0.

I am sure I am missing sth very obvious, but could you pls help?

The above code works if I contain the function and the algorithm parts in the same fie, but I would like to separate them.

Thank you

The error is pretty minute, the only reason the value is not updated is because you forgot to assign the value to the variable y The code in the second file(test1) should be:

import test as t
y = 0
y = t.tests(y)
print("New value is " + str(y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM