Getting UnboundLocalError error while using string counting

Question:

I got this error UnboundLocalError: local variable 'total' referenced before assignment while running the code below.
First sorry for asking this silly question, I know it’s very easy one but I don’t seemed to understand it somehow, so thought to ask you guys.

total = 0
def count(string, letter):
    for x in string:
        if x == letter:
            total +=1
    print(y)

as per my knowledge the total has been assigned before the function so it should be Global variable and can be used anywhere in the script.
when I used


def count(string, letter):
    total = 0
    for x in string:
        if x == letter:
            total +=1
    print(y)

when I ran this, using assignment of total inside the function it worked fine. But I want to know why I got the error above at first place.
Please explain me. I’m learning it by my own with a pdf and help of you guys.

Thanks in advance

Asked By: Saurabh

||

Answers:

Yes, “total” variable must be declared/defined inside the count(string, letter) function. In Python a function can’t access an outer/global variable like a function in JavaScript, except passing an outer variable to that function as an argument like so count(string, letter, total), but previously we need to define the function with theses three parameters instead.

Answered By: dqve
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.