简体   繁体   中英

Changing variable values with functions in Python

Like, I ll write a simple program for explanation.

hi=1
hii=2

def change():
    hi=3
    hii=4
    
for i in range(0,1):
    change()
    print(hi,hii)

Output is 1 2

But I want 3 4. How can I achieve this?

You need to re-assign those values:

def change()
    return 3, 4

hi = 1
hii = 2

print(hi, hii)
1 2

hi, hii = change()

print(hi, hii)
3 4

You need to use global to achieve this but keep in mind that this is not a recommended practice because of the overhead global bring with itself:

hi=1
hii=2

def change():
    global hi, hii
    hi=3
    hii=4
    
for i in range(0,1):
    change()
    print(hi, hii)

You must make the variables global first like as below

def change():
    global hi
    global hii
    hi=3
    hii=4

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