r/cs50•
Trollcontrol

Readability sentimental (Python) comparing characters question

Spoilersentimental

Hi guys, I have had problems in regards to counting sentences.

It leads me to a more general Python question.

Comparing the looping character c to '.' '?' and '!' got my code working in check50

def count_letters(text):
 letters = 0
 words = 1
 sentences = 0

 for c in text:
     if c.isalpha():
         letters += 1
         continue
     if c.isspace():
         words += 1
         continue
     if c == ".":
         sentences += 1
         continue
     if c == "!":
         sentences += 1
         continue
     if c == "?":
         sentences += 1
         

However the more elegant syntax solution, does not work ! it counts other characters like apostrophes ' as a sentence as well. I am at a loss why, and was hoping someone could explain this to me, thank you

def count_letters(text):

letters = 0 words = 1 sentences = 0

for c in text: if c.isalpha(): letters += 1 continue if c.isspace(): words += 1 continue if c == '.' or '?' or '!': sentences += 1

Thanks for taking a look really appreciate it

Posted Apr 27, 2023, 6:07 PM UTC

12
Loading comments…