How to change a global variable inside a function and vice versa? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to change a global variable inside a function and vice versa?

This doesn't work: https://code.sololearn.com/cgZSs6WEU5qZ/?ref=app

1st Apr 2021, 5:49 AM
Carlos
Carlos - avatar
6 Answers
+ 3
You can use "global" keyword to define a global variable inside the function to access it across the function Here's how 👇 https://code.sololearn.com/czPAkBDJSYT0/?ref=app
1st Apr 2021, 5:53 AM
Arsenic
Arsenic - avatar
+ 1
No, unlike global variables, local variables are meant to be used/accessed in a local scope only, meaning you can't access that "a" outside the function.
1st Apr 2021, 6:03 AM
Arsenic
Arsenic - avatar
0
Is vice versa possible? Like in: def func(): a = 8 print(a) can we change "a" outside the function?
1st Apr 2021, 6:00 AM
Carlos
Carlos - avatar
0
Carlos, you can do this: def func(): a = 8 return a a = func() # a=8 a += 2 print(a) # a=10
1st Apr 2021, 6:34 AM
Tomas Konecny
0
Tomáš Konečný That doesn't change the variable inside the function though.
1st Apr 2021, 6:37 AM
Carlos
Carlos - avatar
0
Carlos I just tried to demonstrate how to operate with variables outside of the function... That was your question in one of your previous posts here
1st Apr 2021, 12:52 PM
Tomas Konecny