Search code examples
pythonedx

how does .isalpha and elif works ? (python)


I want to create a code that prints words in uppercase (after "G") from a sentence

# [] create words after "G"
# sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)

# Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

here is my code

q = input ("Quote : ")

word = ""
for a in q :
    if a.isalpha() == True :
        word = word + a
    elif word[0].lower() > "g" :
        print (word.upper())
        word = ""
    else :
        word = ""

it runs well until the last word of the sentence, it can't print the words although the first letter is after "G". Also, when it found punctuation, it stuck, and says

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-45-29b3e8e00230> in <module>()
      8     if a.isalpha() == True :
      9         word = word + a
---> 10     elif word[0].lower() > "g" :
     11         print (word.upper())
     12         word = ""

IndexError: string index out of range

I'm suspicious it has something whether with the .isalpha or the elif

I need to know how to fix it and where do I made mistakes


Solution

  • If you have two characters in succession that are not letters (such as a comma followed by a space), then you will hit elif word[0].lower() > "g" when word is the empty string, so there will be no character at word[0]. That is what causes the exception.

    Simplistically, you could avoid this by checking word isn't empty before you try and get word[0].

    elif word and word[0].lower() > "g":
    

    That at least should avoid the exception.


    But I still have the last word issue, it doesn't print the last word although it started with alphabet greater than "G"

    You only print when you hit a non-alphabetic character. So if you pass a word and then don't hit a non-alphabetic character, then the last word will not be printed.

    To solve that, you can add a print after the end of your loop, in case there is a final word still to be printed.

    for a in q:
        ... etc.
    
    if word and word[0].lower() > 'g':
        print(word)