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[i] == " ":
(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[i] != " ":
print(sentence[i])
i += 1
stop = True
else:
stop = True
while stop == True:
if sentence[i] == " ":
stop = False
i += 1
break
else:
i += 1
The problem arises (as long as your sentence ends in a non-space character) within the inner while
block.
For your particular sentence of length 27, consider what occurs when i
is 26: we increment i
to make i
become 27 in the else
block of the inner while
block, and then go back to the top of the inner while block.
You might have expected that the while i < len(sentence)
condition to kick in and have us exit the program, but that check only occurs once you hit the bottom of the OUTER while block, which can only occur if we exit the inner while block. Since we never make that check, the program continues and we hit the problematic if sentence[i] == " "
.
One quick solution that would make this code work is to change the condition of the inner while loop to while stop == True and i < len(sentence):
.
That said, I personally would implement things differently. Consider the following code, which yields the same result:
sentence = "Humpty Dumpty sat on a wall"
previous_space = True
i = 0
while i < len(sentence):
if sentence[i] == " ":
previous_space = True
elif previous_space:
print(sentence[i])
previous_space = False
i += 1
Some other notes on your code:
stop
consider dividing your loop into a stop == True
track and stop == False
track rather than using an inner loop.not stop
instead of stop == False
, since these do the same thing but not stop
is considered more "Pythonic".Here's another alternative that follows your original logic more closely:
stop = False
i = 0
while i < len(sentence):
if stop:
stop = sentence[i] != " "
elif sentence[i] != " ":
print(sentence[i])
stop = True
i += 1
(it seems the other answer beat me to the punch here)