Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python UnboundLocalError: local variable 'count' referenced before assignment

count = 0

def checkletters(string):
    for letter in string:
        count +=1
input = input("What string do you want me to check for letter count: ")
checkletters(input)
print(f"There are {count} letters in that string")

I want the script to ask the user to input a string and it will send the amount of letters in the string

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are many ways to resolve this issue i have two for you

1. make you count variable global

global count

    count = 0
    def checkletters(string):
        for letter in string:
            global count
            count +=1
    input = input("What string do you want me to check for letter count: ")
    checkletters(input)

print(f"There are {count} letters in that string")

2. By using count variable inside the function and returning value from that func..

def checkletters(string):
    count = 0
    for letter in string:
       count +=1
    return count 
input = input("What string do you want me to check for letter count: ")
checkletters(input)
print(f"There are {checkletters(input)} letters in that string")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading