Submit a well-formatted pull request to our class blog with embedded Trinket programs for the below three exercises from Chapter 5 (use these instead of the ones in the book - I added a few explanations). Complete these on your own, using only the materials in this Chapter. Do not look at other students’ submissions until after you’ve completed your work.
After your programs are done, check other students’ work and other resources online if you had questions. Include a reflection about what you think you’ve learned and any concepts that are still fuzzy to you. Did you encounter frustrating situations? Did you feel a lightbulb turn on?
Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
Exercise 3:
The following program counts the number of times the letter a appears in a string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter. The variable count
is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result: the total number of a’s.
Encapsulate this code in a function named counter
, and generalize it so that it accepts the string and the letter as arguments.
Exercise 4:
There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method at https://docs.python.org/3.5/library/stdtypes.html#string-methods and write an invocation that counts the number of times the letter a occurs in “banana”.
Exercise 5:
Take the following Python code that stores a string:`
str = 'X-DSPAM-Confidence: 0.8475'
Use find
and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.