[Python] IndexError when the index is in range

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am doing a beginner python course (so I know it's basic) and this one question has me stumped. The goal is to print the first letter of every word in a sentence, and my method has been to go through every letter of the string, testing if it is a space, after which the program will print the next letter after the space. Everything seems to be running fine, but I get an index error at if sentence == " ": (line 12). I don't know why this is happening because this index error only happens between the first and second outputs, especially because the index seems to be in range of the string.

    sentence = "Humpty Dumpty sat on a wall" #input("Please type in a sentence: ")
    stop = False
    i = 0
    while i < len(sentence):
    if stop == False and sentence != " ":
    print(sentence)
    i += 1
    stop = True
    else:
    stop = True
    while stop == True:
    if sentence == " ":
    stop = False
    i += 1
    break
    else:
    i += 1

    Continue reading...

Compartilhe esta Página