Python Forum
sys.stdin to do a word count based on user entry
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sys.stdin to do a word count based on user entry
#4
break takes you out of the inner loop, but you are still stuck in the outer loop. An easy way to break out of both is make this a function and use return.
def get_word_count():
    count = {}
    for line in sys.stdin:
        for word in line.split():
            if word == 'submit':
                return count
            count[word] = count.get(word,0) + 1

for key,value in get_word_count().items():
    print(key,value)
I see this a lot and it makes me wonder where it comes from. There is no reason to for the else in this code:
        if word == 'submit':
            break
        else:  # Does nothing!
            dictionary_words[word] = dictionary_words.get(word,0) + 1
If the word is 'submit' it will break out of the loop and not update the word count. If the word is not submit it will update the word count in the dictionary. The code does the same thing with or without the else.
Reply


Messages In This Thread
RE: sys.stdin to do a word count based on user entry - by deanhystad - Jul-19-2020, 01:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a menu and execute a function based on user selection in python? Thedarkphoenix 1 1,344 Nov-23-2022, 07:53 PM
Last Post: Larz60+
Question Simulate an answer based on user input [Beginner needs guidance] Bombardini 1 1,304 Nov-12-2022, 03:47 AM
Last Post: deanhystad
  Word count vanjoe198 1 1,979 Mar-16-2021, 12:27 AM
Last Post: BashBedlam
  Changing Directory based on user input paulmerton4pope 13 8,109 Aug-14-2020, 11:48 AM
Last Post: GOTO10
  Writing a function that changes its answer based on user input SirRavenclaw 2 2,830 Dec-21-2019, 09:46 PM
Last Post: Clunk_Head
  count unique letters in a word sunny_awesome 4 8,750 Jun-06-2019, 07:15 PM
Last Post: kotter
  Word based Game of 21 DatNerdKid 2 78,826 Aug-24-2018, 03:25 PM
Last Post: DuaneJack
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,217 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

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