简体   繁体   中英

change value of variable outside function

I want to increment p with the help of function and use it in another function, eg

p = 0
def o():
    global p
    p += 1
    print(p)
    return(p)

In this code I want to use the value of p after running the function multiple times.

The output from " print() " and " return " in the function are as expected but I need the value of p to change too. How can I change the value of p too? I have tried to use another variable to get the value of p to but it didn't work.

Your code works fine.

p = 0
def o():
    global p
    p += 1
print(p) # -> 0
o()
print(p) # -> 1

But I would recommend putting the p variable inside the (), that would make the code way cleaner and you can prevent more errors and bugs in bigger and more complex systems.
Happy coding!

Having a function manipulate a global value like you implemented is usually not the way to go. Since this function could be called by you or a collaborating programmer from everywhere this could alter a variable you depend on in a different area of your script. Furthermore you might want to be able to use the same function to increment different variables.

Therefore a solution like this would be preferable:

def increment(value_to_increment):
    value_to_increment += 1
    return value_to_increment

p= 0
p = increment(p)
print(p)

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