Feb-12-2018, 11:21 PM
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:
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.
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
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()) |