Why does this code only work when entering all capital letters?

After a good study, I could not find why this code counts uppercase letters in a sentence when they are all capitalized, but will consider "0" capital letters if I were to enter a sentence that contains any lowercase letters, for example: "Hello World" .

 message = input("Enter your sentence: ") print("Capital Letters: ", sum(1 for c in message if message.isupper())) 
+5
source share
1 answer

Because the condition in your if clause if wrong; the isupper method returns True if all characters in a given string are capitalized:

 >>> "UPPER".isupper() True >>> "UPPEr".isupper() False 

See the documentation for str.isupper :

Return True if all circled characters in str uppercase, and otherwise in str , False there is at least one oval character.

(Emphasize mine)

Since you are checking message for message.isupper(() , this returns False all the time, resulting in a sum of 0 .

Instead of checking the complete message with message.isupper() , use if for each character with if c.isupper() for each c in message :

 print("Capital Letters: ", sum(1 for c in message if c.isupper())) 

You can also take advantage of the fact that True acts as 1 and False as 0 to trim this a bit if you want:

 print("Capital Letters: ", sum(c.isupper() for c in message)) 

or, if you like functional approaches, a map function for your input:

 print("Capital Letters: ", sum(map(str.isupper, message))) 

Even if they may, subjectively, look better; they tend to be more mystical than the original approach (and slightly less effective).

+9
source

Source: https://habr.com/ru/post/1262705/


All Articles