Why n is 0 in the out put why not 4 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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))

8th Oct 2018, 11:31 AM
AMAN TOMAR
AMAN TOMAR - avatar
5 Answers
+ 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.
8th Oct 2018, 11:51 AM
Anna
Anna - avatar
+ 2
You're welcome 😊
8th Oct 2018, 12:09 PM
Anna
Anna - avatar
+ 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)
9th Oct 2018, 2:41 AM
And Chur
And Chur - avatar
+ 1
thank you😅😅
8th Oct 2018, 12:00 PM
AMAN TOMAR
AMAN TOMAR - avatar
8th Oct 2018, 11:31 AM
AMAN TOMAR
AMAN TOMAR - avatar