What did I do wrong?
When your process encounters the comma (not-alpha) after the word go
it determines that go
does not start with a letter greater than 'g'
so it assigns an empty string to word
(else; word = ''
). The next item is a space which is not-alpha and it tries to compare the first letter of word
which is an empty string (''[0] > 'g'
) so it causes an IndexError.
You can fix it by checking to see if word
is an empty string before the comparison.
Change
if word.lower()[0] > "g":
to
if word and word.lower()[0] > "g":
An empty string evaluates to a boolean False:
>>> s = ''
>>> bool(s)
False
>>>
and
is a boolean operation; x and y
will evaluate to False
if either term is False - x
is evaluated first; if it is False
, its value will be returned and y
will not be evaluated. This is referred to as short circuit behavior.
>>> x = ''
>>> y = 'foo'
>>> x and y
''
>>> bool(x and y)
False
>>> if x and y:
... print(True)
... else:
... print(False)
False
>>>
My fix for your conditional statement relies on the short-circuit behavior so that word[0]...
won't be evaluated if word
is an empty string. Your else
clause could be written a little more explicit - something like:
....
else:
if not word:
pass
elif word.lower()[0] > "g":
print(word)
word = ""
but for some reason I didn't like how that looked.