Tim Cooke

Exercises for Programmers (Python): 3 of 57 - Printing Quotes

29th July 2020

Exercise 3 in book Exercises for Programmers: 57 Challenges to Develop Your Coding Skills by Brian P. Hogan.

Create a program that prompts for a quote and an author. Display the quotation and author as shown in the example output.

Example Output

What is the quote? These aren't the droids you're looking for.
Who said it? Obi-Wan Kenobi
Obi-Wan Kenobi says, "These aren't the droids you're looking for."

I'll start with a test. Again I'm making assumptions about the structure of the code and expecting a function called quotation() that takes a string author and a string quote and returns the output sentence.

import unittest
import qoutes


class TestQuotes(unittest.TestCase):

    def test_givenPlainQuote_returnQuotationOutput(self):
        self.assertEqual(quotes.quotation('Michael Barry', 'If in doubt, git checkout'),
                         "Michael Barry says, \"If in doubt, git checkout\"")

A nod to a favourite quote (of his and mine) from a past colleague Michael Barry. As expected this test fails because I haven't written any implentation yet, so let's get right to it. My initial thoughts were that I'd need to do all sorts of parsing and special handling of the quotes in the passed in string but it turns out all I need to do is figure out how to print the " symbol inside a string. As is common in many languages the backslash \ is the escape character, meaning \" is the double quote string literal.

def quotation(who, says):
    return who + " says, \"" + says + "\""

That test text didn't contain any quote characters so let's write another test to see if they're handled.

def test_givenTextWithQuotes_returnQuotationOutput(self):
    self.assertEqual(quotes.quotation('Obi-Wan Kenobi', 'These aren\'t the droids you\'re looking for.'),
                     "Obi-Wan Kenobi says, \"These aren\'t the droids you\'re looking for.\"")

Yup, all good

$ python3 -m unittest
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Using the same __main__ trick for handling terminal io

if __name__ == "__main__":
    quote = input("What is the quote? ")
    who = input("Who said it? ")
    output = quotation(who, quote)
    print(output)
$ python3 quotes.py 
What is the quote? These aren't the droids you're looking for.
Who said it? Obi-Wan Kenobi
Obi-Wan Kenobi says, "These aren't the droids you're looking for."

Learning review

Github

57-exercises-python/03-printing-quotes/