Defined function is miscounting number of upper/lowercase characters
Question:
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.
Answers:
.islower() isn’t a method I’m aware of :). You must have meant .lower().
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')
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.
.islower() isn’t a method I’m aware of :). You must have meant .lower().
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')