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

Defined function is miscounting number of upper/lowercase characters

def letcheck(a):
    upper = 0
    lower = 0
    for letter in a:
        if a.islower():
            lower += 1
        else:
            upper += 1
    print('The number of lowercase letters is', lower)
    print('The number of uppercase letters is', upper)
    return

letcheck('My name is Slugcat')

Hi there. I imagine this is very basic for most of you so forgive me but I can’t figure out why my function is outputting this.

The number of lowercase letters is 0
The number of uppercase letters is 18

Process finished with exit code 0

Why has it counted all characters as uppercase? Please help.
P.S. is there any way to stop it from counting the spaces in the string? Thank you very much.

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

>Solution :

Change if a.islower() to if letter.islower() as you want to check the case for each letter not a which is the sentence itself. Spaces are counted as uppercase so for an accurate reading loop over the sentence with the whitespace removed.

def letcheck(a):
    upper = 0
    lower = 0
    #Loop over sentence with whitespace removed
    for letter in a.replace(" ",""):
        if letter.islower():
            lower += 1
        else:
            upper += 1
    print('The number of lowercase letters is', lower)
    print('The number of uppercase letters is', upper)
    return

letcheck('My name is Slugcat')
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