0

My code is right below I am unable to find the issue because my C code for readability was basically the same(except syntax and formatting of course!) and it was working perfectly. This Python code is giving greater than expected results for example it gave grade 9 for a grade 2 sentence. Please help, thanks!

from cs50 import get_string

text = get_string("Text: ")
num_words = num_sentences = num_letters = i = 0
LEN = len(text)
while i < LEN:
    if text[i].isalpha:
        num_letters += 1
    if (i == 0 and text[i] != " ") or (i != LEN and text[i] == " " and text[i + 1] != " "):
        num_words += 1
    if text[i] == "." or text[i] == "?" or text[i] == "!":
        num_sentences += 1
    i += 1

L = (num_letters / num_words) * 100
S = (num_sentences / num_words) * 100
index = round(0.0588 * L - 0.296 * S - 15.8)
if index < 1:
    print("Before Grade 1")
elif index >= 16:
    print("Grade 16+")
else:
    print(f"Grade {index}")
1
  • 1
    'text[i].isalpha()' will do the trick – Tritum Jun 7 '20 at 11:43
0

Your code is calculating the num_letters wrong - it's counting the spaces and punctuation marks as well. Just put a print(num_sentences, num_words, num_letters) after getting out of the while-loop as a sanity check.

2
  • It helped me identify the problem and @Tritum 's comment was the solution thanks both of you but I'm confused as to why isalpha was including spaces and punctuation without parantheses – ammar79797 Jun 7 '20 at 20:55
  • Glad I could help (do please upvote for later readers, btw.) As for your related question, without the parentheses, you are not actually calling isalpha. See this thread: stackoverflow.com/questions/44994823/…. So, basically python is just ignoring that line and moving on to the counter. – user3671 Jun 8 '20 at 10:28

You must log in to answer this question.

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