0

I'm having trouble getting an accurate value of the index. The output ends up being a negative number so the result always turns out as before grade one. I'm not sure where I went wrong

    from cs50 import get_string
    import string

    s = get_string("Text: \n")
    s = s.lower()

    num_letters = 0
    num_words = 0
    num_sentences = 0
    n = len(s)

   for i in range(n):
       if s.isalpha() == True:
        num_letters += 1

if s[i] == '.' or s[i] == '!' or s[i] == '?':
    num_sentences += 1

if (i == 0 and s[i] != ' ') or (i != n - 1 and s[i] == ' ' and s[i + 1] != ' '):
    num_words += 1

L = (num_letters / num_words) * 100
S = (num_sentences / num_words) * 100

index = (0.0588 * L - 0.296 * S - 15.8)
0

From the python doc (emphasis added):

str.isalpha()

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

Since space and punctuation are not letters s.isalpha() is always False.

0

Your code may not be doing what you think it's doing. Look at this block:

   for i in range(n):
       if s.isalpha() == True:
            num_letters += 1

Though the first line calls for iterating over i, the rest of it does not actually have any i to iterate over. So your num_letters is staying at 0.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .