Back to Module 2

Exercises

Work through these steps in order. The goal is to practice values, variables, functions, and methods in one small activity.

Exercise 1. Build a sentence variable

Create a variable named string_sent and store a sentence about yourself.

Example:

string_sent = "I like running trails and drinking cold brew."

Exercise 2. Count the characters

Use len() to count how many characters are in the sentence.

print(len(string_sent))

Question:

  • Does the count include spaces and punctuation?

Exercise 3. Split the sentence into words

Use the string method .split() and save the result in a variable named list_sent.

list_sent = string_sent.split()
print(list_sent)

Expected result:

  • You should see a list of words.

Exercise 4. Count the words

Use len() again, this time on list_sent.

print(len(list_sent))

Exercise 5. Find the average number of characters per word

Create a variable named av_chars.

av_chars = len(string_sent) / len(list_sent)

Then print the result in two ways.

print(av_chars)
print(str(av_chars))

Question:

  • What is the difference between printing the number itself and converting it with str()?

Exercise 6. Try your own version

Change the sentence and run the code again.

Try one short sentence and one longer sentence. Then compare:

  • character count
  • word count
  • average characters per word

Full starter code

string_sent = "I like running trails and drinking cold brew."

print(len(string_sent))

list_sent = string_sent.split()
print(list_sent)

print(len(list_sent))

av_chars = len(string_sent) / len(list_sent)
print(av_chars)
print(str(av_chars))

Back to Module 2