0

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?

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

By overhead, do you mean the computational cost? If so, can you please explain why?
Not computational cost but code management overhead since there can be many methods that can change the global variable and it becomes difficult to debug whenever there are issues.
1

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

1 Comment

Yeah, I wanted to find a way without using return.. But thanks :D
0

You must make the variables global first like as below

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.