In class exercise python5
Exercise · Explain This Python Function (Word Frequency Counter)
Python · Intermediatedef count_words(sentence):
word_counts = {}
words = sentence.lower().split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return dict(sorted(word_counts.items()))
text = "Python is fun and Python is powerful"
print(count_words(text))
🎯 Instructions oral task
- Explain what the function does.
- Describe why
lower()is used. - Explain what
split()does. - Explain why an empty dictionary is created.
- Describe how the loop counts each word.
- Explain how the dictionary is sorted.
- State the final output.
📖 Vocabulary core
- frequency — how many times something appears.
- dictionary — a collection of key-value pairs.
- key — the unique identifier in a dictionary.
- value — the data associated with a key.
- normalize — convert data into a consistent format.
- alphabetical order — sorted from A to Z.
- string method — a built-in function used on text.
🧩 Collocations natural English
- count word frequencies
- convert text to lowercase
- split a sentence into words
- store values in a dictionary
- update the counter
- sort the results alphabetically
- return the final dictionary
🗣️ Phrasal Verbs interview speech
- break down — "The function breaks down the sentence into individual words."
- keep track of — "The dictionary keeps track of each word count."
- go through — "The loop goes through every word in the list."
- end up with — "We end up with a dictionary containing every word and its frequency."
🎤 Model Answer spoken
This function is called count_words. Its purpose is to count how many times each word appears in a sentence.
First, an empty dictionary called word_counts is created to store the frequency of each word.
The code then calls lower() to convert every character to lowercase. This normalizes the text so that words like "Python" and "python" are treated as the same word.
Next, the split() method separates the sentence into a list of individual words using spaces.
The for loop iterates through each word. If the word already exists as a key in the dictionary, its value is incremented by one. Otherwise, a new key is created with an initial value of one.
Finally, the dictionary is sorted alphabetically using sorted(), converted back into a dictionary, and returned by the function.
The final output is:
{
'and': 1,
'fun': 1,
'is': 2,
'powerful': 1,
'python': 2
}