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 in Python by Vishal
68 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 by Omkar
• 67,660 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
115 views
0 votes
1 answer
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 in Python by Mohammad
• 3,060 points
44 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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 339 views
+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
• 67,660 points
1,822 views
0 votes
2 answers