+ 3

I cant chance variables with def

I wrote a code like this and ran it: --------------- a=10 b=10 def func(): a+=5 b-=5 func() print(a,b) ---------------- I got an error message. I don't know why it is not working. Where did I make mistake?

8th May 2018, 1:48 PM
Ayastar
Ayastar - avatar
15 Answers
+ 5
#Finally got it. a=10 b=10 def func(): #tell explicitly to use a and b global a global b a+=5 b-=5 func() print(a,b)
8th May 2018, 2:22 PM
Timon Paßlick
8th May 2018, 4:00 PM
Uni
Uni - avatar
+ 7
Timon Paßlick thank you I don't use python very often so I didn't know we could write that. By the way I'm sorry I haven't noticed your previous answer.....😥😧
8th May 2018, 4:05 PM
Uni
Uni - avatar
+ 7
Timon Paßlick oh I don't know if it works I thaught it did since you posted it......
8th May 2018, 4:09 PM
Uni
Uni - avatar
+ 4
you should try this a = 10 #actually no need to define this b = 10 #actually no need to define this def func(a=10,b=10): print(str(a+5) + "," + str(b-5)) func()
8th May 2018, 2:15 PM
Fery Ardiansyah
Fery Ardiansyah - avatar
+ 3
No, It works like this. But if you use them in def, it not works.
8th May 2018, 2:05 PM
Ayastar
Ayastar - avatar
+ 3
Timon it worked and easy. Ty (^-^)
8th May 2018, 2:34 PM
Ayastar
Ayastar - avatar
+ 2
GLOBAL a = 10 Maybe, not sure.
8th May 2018, 1:52 PM
Timon Paßlick
+ 2
I tried all of them. Not working. Can anyone fix this code and send me?
8th May 2018, 2:02 PM
Ayastar
Ayastar - avatar
+ 2
Try to avoid += and -=, maybe Python doesn't support it.
8th May 2018, 2:03 PM
Timon Paßlick
+ 2
Ayastar I'm officially too dumb, sorry.
8th May 2018, 2:07 PM
Timon Paßlick
+ 2
Ok, so, func actually has no idea that a and b exist. It doesn't know anything outside of itself. So here's how you do what you're trying to do: a = 10 b = 10 def func(x, y): x+=5 y-=5 return x,y a, b = func(x,y) print(a,b)
8th May 2018, 2:17 PM
Vlad Serbu
Vlad Serbu - avatar
+ 2
So that was correct? I found it not to work and therefore, I deleted the post mentioning you.
8th May 2018, 4:06 PM
Timon Paßlick
+ 2
Uni You're faster than I can delete. ( ;
8th May 2018, 4:20 PM
Timon Paßlick
+ 1
put the print statement inside the function and try running again.
8th May 2018, 1:53 PM
Jima