Python Forum
Program: Words after "G"/"g"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program: Words after "G"/"g"
#1
Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z

Sample input:
enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with all your heart

Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

split the words by building a placeholder variable: word
loop each character in the input string
check if character is a letter
add a letter to word each loop until a non-alpha char is encountered

if character is alpha
add character to word
non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
else
check if word is greater than "g" alphabetically
print word
set word = empty string
or else
set word = empty string and build the next word


solution:
quote = input("Quote: ")
word = ''
for letter in quote:
    if letter.isalpha():
        word += letter
    elif word.lower() >= 'h':
        print(word.upper())
        word = ''
    else:
        word = ''
if word.lower() >= 'h':
    print(word.upper())
I don't quite understand this solution ( although it works! ). Let's say that my quote is "Apples are better than oranges". That will exclude the first word but how? After the if statement is satisfied ( .isalpha as "apples" is a word ) it will add "apples" to word. How does it skip this if statement and goes to elif? How does program know that although "apples" is a word it shouldn't print it because it starts with letter before 'h'? If there wasn't the if statement with .isalpha test I would understand it but this way it looks like that after if statement the program executes elif. I hope that my question is clear, if not please let me know.
Reply
#2
a string letter would be ordered by its ascii number
>>> ord('a')
97
>>> ord('b')
98
>>> 'a' > 'b'
False
>>> 'b' > 'a'
True
>>> 
So the first if condition: if the letter is alphabetic it just adds the letter to the buffer (word), and passes by all the other conditions and continues to the next iteration of the loop. Whenever a letter comes up in the sentence that is h or more it prints the buffer and then clears it ready for the next word.
Recommended Tutorials:
Reply
#3
Thanks, but I thought that if and elif/else conditions are exclusive. In other words if if condition is satisfied it doesnćt go to elif but to another input, in this case a letter.
Reply
#4
(Feb-15-2018, 10:17 PM)Truman Wrote: In other words if if condition is satisfied it doesnćt go to elif
This is correct. The elif or else conditions does not execute if the line if letter.isalpha(): is true and runs its block. Thats why i said...
(Feb-14-2018, 09:57 PM)metulburr Wrote: and passes by all the other conditions and continues to the next iteration of the loop
(Feb-14-2018, 09:57 PM)metulburr Wrote: Whenever a letter comes up in the sentence that is h or more it prints the buffer and then clears it ready for the next word.
This is on the next iteration


printing can help understand the control flow. print word and letter a lot
Recommended Tutorials:
Reply
#5
I am a novice, just started learning Python a few days back. I need help in understanding the code, so I will try to explain it line by line,but please correct any errors I make:
1: Take a quote from user
2: Define variable "word" as blank
3,4: Each character from quote is taken, and checked whether it is an alphabet.
5: If it is an alphabet, then added to word
6: [I don't understand why elif is written, when an if statement might have sufficed].. picks out letters including and after H
7: Prints them in uppercase
8,9,10 : Don't understand :\
11,12 This just seems like a repetition of 6 and 7
Reply
#6
Basically this task is to determine whether word starts with letters h-z and if so print word in uppercase (it's unclear whether it only h-z or uppercase also; following code assumes that both cases).

It seems to me that easiest way is to use ascii letters position. H-Z is range(72,91) and h-z is range(104, 123). We just create list from these ranges and check using ord() whether first letter of word in range. If so, we print word in uppercase:

>>> quote = 'Wheresoever you go, go with all your heart'
>>> h_z = list(range(72, 91)) + list(range(104, 123))
>>> for word in quote.split():
...     if ord(word[0]) in h_z:
...         print(word.upper())
...
WHERESOEVER
YOU
WITH
YOUR
HEART
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(Aug-31-2018, 11:24 AM)techbaron13 Wrote: 6: [I don't understand why elif is written, when an if statement might have sufficed].. picks out letters including and after H

I'm a novice too and it was really hard to understand, this is my take:
"elif word.lower() >= 'h':"
elif will be executed when an non alpha is founded. so when a space or a comma is found.
If the WORD variable built until now start with a letter >= h ...
"print(word.upper())"
you print the variable WORD
but if not >= h
else: word = '' ... you cancel the variable without printing and then the variable WORD is resetted and the loop goes on building the next word letter by letter until the nex non alpha.
"11,12 This just seems like a repetition of 6 and 7"
this print just the last WORD stored which it does not enter the elif because you don have a non alpha at the end (but if you put a fullstop or a comma or maybe a space I think you dont need it)
Reply
#8
@silverdog your explanation is correct. One can make the code clearer by separating the tasks of splitting the quote into words from the task of comparing to 'h' and printing uppercase. Here is a way
def words(quote):
    word = ''
    for letter in quote:
        if letter.isalpha():
            word += letter
        elif word:
            yield word
            word = ''
    if word:
        yield word

while True:
    quote = input("Please enter a quote: ")
    if quote in ('quit', 'exit'):
        print("Thanks for playing")
        break
    for word in words(quote):
        if word >= 'h':
            print(word.upper())
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020