简体   繁体   中英

Saving the output of a function

I want to change the value of a variable through a function but python functions do not modify a variable when run. For example:

import random as r
x=2
def add(x):
   x=x+r.randint(5,10)
   print x
add(x)
print x

the function variable x, shows something like 8 while the other x is 2. Adding the line:

x=add()

will cause the two to be nonequivalent. How can i save the variable from a function, modifying the old.

you can change you function like this :

    import random as r
x=2
def add(x):
   x=x+r.randint(5,10)
   print (x)
   return (x)
x=add(x)
print x

Your add function, this will also return None. Using no return at all, that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

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