Python Forum
why am I getting "local variable 'x' referenced before assignment"?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why am I getting "local variable 'x' referenced before assignment"?
#1
Given an array of ints (as a list), print the sum of all the elements.
My code:
L=[1, 1, 1, 2]
x=0
def sum3(nums):
    for i in nums:
        x+=i
print(sum3(L))
How is x a local variable if I define it outside of the loop?
Reply
#2
x is defined outside the scope of the function sum3.
Global variables are frowned upon, and there are better methods of doing this,
however adding global x as the first statement (before the if) will solve for now.
Reply
#3
What do you mean before the if?
Reply
#4
he meant for not if
however you don't want it to be global
just move the x = 0 line in the function.
Then you will face a new problem, because your function does not return anything, so it will return None and that's what you will get printed.... You need to fix this as well.

Note that this is not the best approach to sum elements of a list. There is built-in function that does the same
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Jun-16-2018, 05:51 AM)buran Wrote: Note that this is not the best approach to sum elements of a list. There is built-in function that does the same

I think it's OP's homework assignment to recreate the built-in function.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
What is the built-in function for this?
Reply
#7
sum
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Rounding exercise: UnboundLocalError: local variable referenced before assignment Drone4four 5 3,406 Sep-06-2020, 09:01 AM
Last Post: ibreeden
  UnboundLocalError: local variable 'a' referenced before assignment fad3r 3 16,543 Jun-20-2018, 05:43 PM
Last Post: nilamo
  variable referenced before assignment Niko047 4 22,937 Aug-04-2017, 07:55 PM
Last Post: nilamo
  local variable 'l' referenced before assignment... darkreaper1959 4 7,431 Jan-21-2017, 08:16 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020