Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code only work when the input is all capital letters?

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()))
like image 247
Jake Schuchmann Avatar asked Jan 12 '17 18:01

Jake Schuchmann


1 Answers

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 in str are uppercase and there is at least one cased character in str, 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).

like image 62
Dimitris Fasarakis Hilliard Avatar answered Sep 24 '22 00:09

Dimitris Fasarakis Hilliard