Python UnboundLocalError error while executing script

0 votes

Hi,

Below is the code i am trying but is showing error, please help with this code.

word = []
def letter(a):
for each in a:
if each.isalpha():
word = word+1
word.append
else:
digit = digit+1
digit.append

#letter(input("The letter with digit : "))
letter("Hello123")
print(word)

Error:

Traceback (most recent call last):

File "", line 13, in 
letter("Hello123")

File "", line 5, in letter
word = word+1

UnboundLocalError: local variable "word" referenced before assignment
Jan 22, 2019 in Python by Vishal
124 views

1 answer to this question.

0 votes

The reason for this error is that the variables word and digit are not accessible inside the function. To overcome the issue you are facing, you need to declare the variables - word, digit as global. Also, define the variables as an integer instead of list as they just store the number of characters and digits in the given string.

Try the below modified Python code and check:

word=0

digit=0

def letter(a):

    global word

    global digit

    for each in a:

        if each.isalpha():

            word=word+1

        else:

            digit=digit+1

#letter(input("The letter with digit : "))

letter("Hello123")

print(word)

answered Jan 22, 2019 by Omkar
• 68,840 points

Related Questions In Python

+2 votes
2 answers

Error while printing hello world in python.

You must be trying this command in ...READ MORE

answered Mar 31, 2018 in Python by GandalfDwhite
• 1,320 points
160 views
0 votes
1 answer

Python error "ValueError: size needs to be (int width, int height)" while using pygame.Surface

pygame.Surface takes in integer values for building ...READ MORE

answered Jun 19, 2019 in Python by Varsha
246 views
0 votes
1 answer

How to resolve the error while importing cv2 from openCV in python?

I would recommend you go with anaconda ...READ MORE

answered Jul 31, 2019 in Python by Mohammad
• 3,210 points
99 views
0 votes
1 answer

Python error "UnboundLocalError: local variable 'x' referenced before assignment"

You get this error because when you ...READ MORE

answered Jul 24, 2019 in Python by Greg
2,263 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 509 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

Python argparse error "NameError: name 'file' is not defined"

The right datatype for destination in argpasrse module ...READ MORE

answered Nov 28, 2018 in Python by Omkar
• 68,840 points
2,401 views
0 votes
2 answers