Python for Everybody

Chapter 6

Exercise 6.1

"""
Exercise 6.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.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""

fruit = 'banana'
index = len(fruit)-1                    # Convert to index
while index >= 0:
    letter = fruit[index]
    print(letter)
    index -= 1                          # Update index
    

Exercise 6.3

"""
Exercise 6.3: Encapsulate this code in a function named count, and generalize
it so that it accepts the string and the letter as arguments.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""

def count(word, letter):
    """"
    Counts the number of times a given letter appears in a word
    Input:  word -- the word in question
            letter -- the letter in the word to count
    Output:prints the number of letters
    """
    counter = 0

    for character in word:
        if character == letter:
            counter = counter + 1
    print(counter)

input_word = input('Enter the word: ')
input_letter = input('Enter the letter: ')
count(input_word, input_letter)
    

Exercise 6.5

"""
Exercise  6.5: Take the following Python code that stores a string:

string = '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 extraced string
into a floating number.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
string = 'X-DSPAM-Confidence: 0.8475'

col_pos = string.find(':')                  # Finds the colon character
number = string[col_pos+1:]                 # Extracts portion after colon
confidence = float(number)                  # Converts to floating point number
print(confidence)