0
Function output
def f(n,v): n = len(v) v.append(n) n=0 v=[8,0,4,6] f(n,v) print(n,sum(v)) output : 0 22 How could it happen? I was expecting 4 22 as an output. Can someone explain please?
5 odpowiedzi
+ 1
The function takes two parameters as a input, but it doesn't actually change the global variable corresponding to the parameter. This means the variables n and v don't actually get changed(but the variables n and v inside the function do), and since n is equal to 0, and the sum of the numbers in v is 22, the output is 0 22. If you want to see this in action, you could put a print() statement inside the function:
print(n, sum(v))
This would return 4 22.
+ 1
Thank you Mr. Chen, I understood now. I need to look at global and local variables. I can change the code for storing n globally now.
+ 1
You can use multiple global variables with the global keyword, just separate them with commas. Just make sure not to name new local variables in the function, or an error will occur.
0
Yes, that could work. You could also directly change it with the global keyword:
x = 5
def change_x(num):
global x #allows function to use global variable x
x = num
change(10) #changes value of x to 10
0
Okay thank you again! I have a question at that point, will it be good for me to use any variable as global in the function? Maybe it might cause some problems for more complex codes