0
from cs50 import get_string


s = get_string("Text: ")
letter = 0
i = 0
word = 1
sent = 0

while s[i] != None:
    if s[i] == ' ':
        word = word + 1
        i = i + 1

    elif (s[i].isalpha()):
        letter =  letter + 1
        i = i + 1


    elif s[i] == "." or s[i] == "!" or s[i] == "?":
        sent = sent + 1
        i = i + 1

    else:
        i = i + 1

grade = 0.0588 * (100 * letter / word) - 0.296 * (100 * sent / word) - 15.8

if grade < 16 and grade >= 0:
    print("Grade", round(grade))

elif grade >= 16:
    print("Grade 16+")

else:
    print("Before Grade 1")

enter image description here

1 Answer 1

1

I think you are expecting to eventually find a NULL character at the end of the string the way you would have in C but Python has an actual string datatype and it'll only let you iterate over the actual characters it contains.

The error in your example occurs when i reaches 40 after running the logic on the final period in your string. s[40] doesn't exist hence the error.

Python let's you find a string's length easily with the len() function. Changing the while condition to the below resolves the error.

while i < len(s)
1
  • yeah it fixed the error i was just trying to find the end of string. thank you :) Commented Jun 4, 2020 at 3:31

You must log in to answer this question.

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