Python Forum

Full Version: [Help] sorted() in while loop with user's input() {Screenshot attached}
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Please see the attached screenshot of my terminal to see what the issue is?
[Image: sorted_zpscfwnb8km.png]

When I pressed Enter on an empty line the program should end & the words entered whould be printed in an alphabetical order.

Please advise what's next? Thank you
=============================================================================================
Here's the exercise that I've been trying to do:
# Building and sorting an array. Write the program that asks us to type as many words as we want (one word per line, continuing until we just press Enter on an empty line) and then repeats the words back to us in alphabetical order. Make sure to test your program thoroughly; for example, does hitting Enter on an empty line always exit your program? Even on the first line? And the second?

# Hint: There’s a lovely array method that will give you a sorted version of an array: sorted(). Use it!
=============================================================================================
Here's my code:

print("[System] Hi! Enter as many words as you want. One word per line until you press Enter on an empty line. This program will then repeat the words in alphabetical order. Ready?!")

empty_line = 0
words_list = []

while True:
	word = input("Enter a word: ")
	words_list.append(word)

	if empty_line == "":
		print("[System] Program Ended...")
		empty_line = 0

words_list.append(word)
after:
    word = input("Enter a word: ")
add:
    word = input("Enter a word: ")
    if len(word(strip()) == 0:
        break
You can use that an empty string is evaluated to False.

>>> s = input()

>>> bool(s)
False
>>> 
words = []
while True:
    word = input('Type a word: ')
    if word:
        words.append(word)
    else:
        break

print(sorted(words))
Thank you for the input, Larz60+ Smile

Wavic, I really appreciate this demo. Heart

>>> s = input()
 
>>> bool(s)
False
>>>
Thank you so so much! See the screenshot of my terminal.

[Image: sorted1_zpscwy8a0lm.png]
In Python, an empty sequence or collection ( list, tuple, dict, etc. ), None, 0 and False of course are evaluated to False.
Wonderful!

Thank you very much, Wavic! :)