+ 1

why is my code not working?

def find_lowest(): n1=int(input('Enter Your Number 1 :- ')) n2=int(input('Enter Your Number 2 :- ')) n3=int(input('Enter Your Number 3 :- ')) n4=int(input('Enter Your Number 4 :- ')) if n1<n2 and n1<n3 and n1<n4: print(n1,'is the lowest') n1=0 elif n2<n1 and n2<n3 and n2<n4: print(n2,'is the lowest') n2=0 elif n3<n1 and n3<n2 and n3<n4: print(n3,'is the lowest') n3=0 elif n4<n1 and n4<n2 and n4<n3: print(n4,'is the lowest') n4=0 def find_avg(): find_lowest() avg=(n1 + n2 + n3 + n4)/4 print(avg) find_avg() its giving me error that n1 is not defined when i run find_avg() on line avg=(n1+n2+n3+n4)/4

8th Sep 2018, 1:18 PM
shaleen agarwal
shaleen agarwal - avatar
3 Answers
+ 4
Because they are in a different scope. You have to pass the variables to the function. Like find_avg(n1,n2,n3,n4) Better define them in your main code (not in some function) and pass them to the respective functions. Or, if you want them to be assigned in some function, return them, so that you can use them in other functions.
8th Sep 2018, 1:30 PM
Matthias
Matthias - avatar
+ 3
shaleen agarwal It won't list all the errors in the code, only the first one. n1 is the first undefined variable the interpreter finds, so it will show that n1 is undefined and stop. However n2 etc. are undefined as well. If you don't want to pass the variables as arguments, you can use global variables too. You just have to declare them outside of both functions and include "global n1, n2" etc. in both functions.
8th Sep 2018, 1:55 PM
Anna
Anna - avatar
0
The why is it Giving me error only about n1 and not others.... I tried returning the values and defining avg's arguments but it didn't work and it only gave me error on n1
8th Sep 2018, 1:49 PM
shaleen agarwal
shaleen agarwal - avatar