After a good while of research, I've been unable to find why this code counts the capital letters in a sentence when they're all capitalized, but will count "0"
capital letters if I were to enter a sentence that contains any lowercase letters, such as: "Hello World"
.
message = input("Enter your sentence: ")
print("Capital Letters: ", sum(1 for c in message if message.isupper()))
Because the condition in your if
clause is flawed; the isupper
method returns True
if all characters in the given string are uppercase:
>>> "UPPER".isupper()
True
>>> "UPPEr".isupper()
False
See the documentation for str.isupper
:
Return
True
if all cased characters instr
are uppercase and there is at least one cased character instr
,False
otherwise.
(Emphasis mine)
Since you're checking on message
with message.isupper(()
this will return False
all the time resulting in a sum of 0
.
Instead of checking on the full message with message.isupper()
, use your if
on a per-character basis with if c.isupper()
for every c
in message
:
print("Capital Letters: ", sum(1 for c in message if c.isupper()))
You could also take advantage of the fact that True
acts like 1
and False
like 0
to slightly trim that down if you'd want:
print("Capital Letters: ", sum(c.isupper() for c in message))
or, if you like functional approaches, map
the function to your input:
print("Capital Letters: ", sum(map(str.isupper, message)))
Even though these might, subjectively, look nicer; they are generally more mystifying than the original approach (and slightly less efficient too).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With