Python Forum
Stranger in our midst
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stranger in our midst
#4
This is ugly. Duplicate code that never seems to be an exact duplicate.
words = []
new_word = input('Enter a word\n')
while new_word.lower() != 'stop':
    words.append(new_word)
    new_word = input('Enter word\n')
  
print(words)
I like this a little better.
while True:
    new_word = input('Enter a word\n')
    if new_word == 'stop':
        break
    words.append(new_word)
No duplicate code, but it is slightly longer and "while True" as the "forever is only a short time" loop looks odd.

But you can combine the benefits of the two with the new "walrus" operator :=
words = []
print('Enter list of words, one per line.  End list with "stop"')
while (word := input()).lower() != 'stop':
    words.append(word)
Short. No duplicate code.

Pascal RULES!!
Reply


Messages In This Thread
Stranger in our midst - by tfak - Mar-22-2021, 09:16 AM
RE: Stranger in our midst - by GOTO10 - Mar-22-2021, 11:40 AM
RE: Stranger in our midst - by Serafim - Mar-22-2021, 01:21 PM
RE: Stranger in our midst - by deanhystad - Mar-22-2021, 03:04 PM

Forum Jump:

User Panel Messages

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