+ 3
Why n is 0 in the out put why not 4
def f(n,v): n=len(v) v.append(n) n = 0 v = [8,0,4,6] f(n,v) print(n,sum(v))
5 ответов
+ 6
n is both a global variable and a local variable in the function f(). They are two different variables. Whatever you do with n within the function f() doesn't affect the value of the global variable n. print(n, sum(v)) prints the global variable n that was set to 0 before. If you want to change the global variable n in the function f(), add "global n" after def f() (same with the variable v). BUT you will need to find a different name for the function parameter n in this case because n can't be a global variable and a function parameter at the same time.
+ 2
You're welcome 😊
+ 2
Aman, thank you for the question and Anna thanks for the answer. For me there is additional question: why n is local variable but v is global variable in the function f()?
def f(n,v):
n=len(v)
v.append(n)
n = 0
v = [8,0,4,6]
f(n,v)
print(n,v)
+ 1
thank you😅😅
0