+ 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?
15 Antworten
+ 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)
+ 8
Maybe this could help:
https://code.sololearn.com/cueKnX0jJx99/?ref=app
+ 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.....😥😧
+ 7
Timon Paßlick oh I don't know if it works I thaught it did since you posted it......
+ 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()
+ 3
No, It works like this. But if you use them in def, it not works.
+ 3
Timon it worked and easy. Ty (^-^)
+ 2
GLOBAL a = 10
Maybe, not sure.
+ 2
I tried all of them. Not working. Can anyone fix this code and send me?
+ 2
Try to avoid += and -=, maybe Python doesn't support it.
+ 2
Ayastar I'm officially too dumb, sorry.
+ 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)
+ 2
So that was correct? I found it not to work and therefore, I deleted the post mentioning you.
+ 2
Uni You're faster than I can delete. ( ;
+ 1
put the print statement inside the function and try running again.