+ 1
[SOLVED] Explain this code
This code is from a question in sololearn challenge. How does the answer is 20 and not 40, since as one called sum(t), t's value should change to 20+20 = 40. And now new value should be assigned to t. Right? t = 20 def sum(t): t+=20 return(t) sum(t) print(t)
2 Respuestas
+ 7
Harsh,
The function modifies the local copy, not the original " t ". So, when the function adds 20 to " t ", it's updating the local copy, making it 40. But the original " t "remains unchanged, still holding the value 20.
# Since the function doesn't modify the original " t ", when you print " t " outside the function, you get the original value, which is 20.
Note_that...
The function works with a copy of t, not the original t.
# If you want to change the original t , you need to assign the result back to t, like "t = sum(t)".
#example1..
you could assign the returned value of the (sum) function.
t = 20
def sum(t):
t += 20
return t
t = sum(t)
print(t)//output..40
#example2...
you could use the "global" keyword..
t = 20
def sum_t():
global t
t += 20
sum_t()
print(t) //output..40
#Hope it's will helpful..
0
Darpan kesharwani Thank you, I understood.