Professional Yapping
LAB5

yapper.png

Welcome

AI chatbots can be quite useful. When they’re not hallucinating, they make...sense. In case you are tired of sensible conversation, let’s write a program to generate trivial, meaningless, or annoying sentences.

Let’s do it. Let’s build our own friendly yapper in Python.

What We Will Learn

More operators Multiline strings Lists Dictionaries Functions that return values Randomization split and join

Activity

Before we write our own yapping program, we’ll get in the mood to chat, by spending some time chatting with Python itself.

REPL Practice

As we start learning more and more about Python, you’ll find the REPL (a.k.a. the shell or interpreter) that we first encountered in Lab 2, more useful. Run the python (or python3) command without any arguments to enter the interpreter and be ready to type at that cute little >>> prompt. Let’s spend several minutes in the REPL. You’ll find it a great practice session, and you can learn so much by experimenting. Here’s a few things to try, together with the responses I got:

>>> 2 + 3
5
>>> 2 < 3
True
>>> 2 == 3
False
>>> 55 ** 21
3528714153412895250897884368896484375
>>> "PYTHON".lower()
'python'
>>> "   Python    or JavaScript?   ".strip()
'Python    or JavaScript?'
>>> pet = "Oreo"
>>> pet[2:]
'eo'
>>> pet * 5
'OreoOreoOreoOreoOreo'
>>> pet + " is such a sweetie"
'Oreo is such a sweetie'
>>> pet[::-1].upper()
'OERO'
>>> "doghouse".startswith("dog")
True
Apostrophes or Quotation Marks for Strings?

It absolutely does not matter. But, if your string contains apostrophes you might want to delimit it with quotation marks, and vice versa. Do you see why? If you want to put apostrophes in an apostrophe-delimited string, or quotation marks in a quotation-mark delimited string, you’ll have do learn about escaping.

Speaking of strings, if your string spans multiple lines you have to triple up the delimiters:

>>> thought_of_the_day = """Over the wintry
Forest, winds howl in rage
With no leaves to blow.

—Natsume Sōseki"""

Lists

Time for something new! Let's practice with lists:

>>> friends = ["Eren", "Mikasa", "Armin"]
>>> friends
['Eren', 'Mikasa', 'Armin']
>>> friends[0]
'Eren'
>>> friends[1]
'Mikasa'
>>> len(friends)
3
>>> friends * 2
['Eren', 'Mikasa', 'Armin', 'Eren', 'Mikasa', 'Armin']
>>> friends + ["Levi", "Hange"]
['Eren', 'Mikasa', 'Armin', 'Levi', 'Hange']
>>> friends.append("Jean")
>>> friends
['Eren', 'Mikasa', 'Armin', 'Jean']
>>> friends[2] = "Sasha"
>>> friends
['Eren', 'Mikasa', 'Sasha', 'Jean']
>>> friends.remove("Jean")
>>> friends
['Eren', 'Mikasa', 'Sasha']
>>> friends.insert(1, "Armin")
>>> friends
['Eren', 'Armin', 'Mikasa', 'Sasha']
>>> friends.index("Mikasa")
2
>>> "Gabi" in friends
False

Dictionaries

Next, let’s become acquainted with dictionaries:

>>> grades = {"Eren": 95, "Mikasa": 98, "Armin": 92}
>>> grades
{'Eren': 95, 'Mikasa': 98, 'Armin': 92}
>>> grades["Eren"]
95
>>> grades["Mikasa"]
98
>>> grades["Armin"]
92
>>> grades["Sasha"] = 100
>>> grades
{'Eren': 95, 'Mikasa': 98, 'Armin': 92, 'Sasha': 100}
>>> grades["Armin"] = 93
>>> grades
{'Eren': 95, 'Mikasa': 98, 'Armin': 93, 'Sasha': 100}
>>> del grades["Eren"]
>>> grades
{'Mikasa': 98, 'Armin': 93, 'Sasha': 100}
>>> grades["Jean"]
Traceback (most recent call last):
  File "<python-input>", line 1, in <module>
    grades["Jean"]
    ~~~~~~^^^^^^^^
KeyError: 'Jean'

Errors

Yep, sometimes things fail. What you saw there in the last one is Python raising an error. In the REPL, you just move on. In a running program, a raised error can crash your program, unless you “handle” it. How exactly we do that is covered later.

Operators

You might have noticed Python has a lot of operators. Here are a few:

OperatorsDescription
+ – * / // % **addition, subtraction, division, floorDivision, remainder, exponentiation
< <= == != >= >lessThan, lessThanOrEqual, equalTo, notEqualTo, greaterThanOrEqual, greaterThan
and or notand, or, not

Try some on your own!

Functions Returning Values

And now, something super important. Previously, we have written functions just to group lines of code together and give them a nice name. The ones we’ve written before just printed things. But the real power of functions comes from their ability to return things. Enter these in the REPL:

def average(a, b):
    return (a + b) / 2

def square(x):
    return x * x

def is_even(n):
    return n % 2 == 0

def capitalized(s):
    return s[0].upper() + s[1:].lower()

You’ll have to get used to entering multiline inputs into the REPL, and you’ll make a lot of mistakes at first, but it does get easier. After each of those functions have been entered, you can call them in the REPL:

>>> average(2, 3)
2.5
>>> square(5)
25
>>> is_even(99)
False
>>> is_even(100)
True
>>> capitalized("hello world")
'Hello world'
>>> capitalized("HELLO WORLD")
'Hello world'

The Yapping Program

Let’s put some of these things together and make a yapping program! Create the folder ~/cmsi1010/lab05, and in it, a new file called yap.py, with the following contents (as always, make sure to ask questions about what’s going on if you don’t understand certain things):

import random

words = {
    "noun": ["dog", "carrot", "chair", "toy", "rice cake"],
    "verb": ["ran", "barked", "squeaked", "flew", "fell", "whistled"],
    "adjective": ["small", "great", "fuzzy", "funny", "light"],
    "preposition": ["through", "over", "under", "beyond", "across"],
    "adverb": ["barely", "mostly", "easily", "already", "just"],
    "color": ["pink", "blue", "mauve", "red", "transparent"]
}

template = """
    Yesterday the color noun
    verb preposition the coach’s
    adjective color noun that was
    adverb adjective before
    """


def random_sentence():
    sentence = []
    for token in template.split():
        if token in words:
            sentence.append(random.choice(words[token]))
        else:
            sentence.append(token)
    return " ".join(sentence) + "."


for _ in range(5):
    print(random_sentence())

Run it.

Challenges

Now it’s your turn. Here are some ideas for you to extend the activities above:

Further Study

We’re making progress with Python. Continue with your reading:

Summary

We’ve covered:

  • More activity in the Python REPL
  • Some new arithmetic and comparison operators
  • Python lists
  • Python dictionaries
  • random.choice
  • split and join

Recall Practice

Here are some questions useful for your spaced repetition learning. Many of the answers are not found on this page. Some will have popped up in lecture. Others will require you to do your own research.

  1. What is the little environment you enter when you invoke the command python (or python3) with no arguments?
    The Python REPL, also known as the Python shell
  2. What do you get when you evaluate the expressions 5 * 3, 5 > 3, and 5 == 3?
    15, True, False
  3. What do you get when you evaluate 21 / 5, 21 // 5, and 21 % 5?
    4.2, 4, 1
  4. How do you delimit a multiline string in Python?
    With triples, either ''' or """.
  5. If s and t are strings, how do we determine whether (a) s and t have the same contents, (b) s starts with t, (c) s ends with t, and (d) s contains t?
    (a) s == t, (b) s.startswith(t), (c) s.endswith(t), (d) t in s.
  6. How do you refer to the third element of the list a?
    a[2].
  7. If pets is the list ["Cinnamon", "Sundae", "Donut", "Brownie", "Cookie", "Benedict The Sixteenth"], how to we get the sublist ["Sundae", "Donut", "Brownie"]?
    With pets[1:4].
  8. If s is a list, what is the difference between s + ["dog"] and s.append("dog")?
    The first creates a new list, while the second modifies the original list in place.
  9. How do you express a dictionary that maps the three countries Colombia, Brazil, and Argentina to their capitals?
    {"Colombia": "Bogotá", "Brazil": "Brasília", "Argentina": "Buenos Aires"}.
  10. What happens when you evaluate d[k] where d is a dictionary and k is a key that is not in the dictionary?
    Python raises a KeyError.
  11. How do you define a function that tells you whether or not a number is positive?
    def is_positive(n):
        return n > 0
  12. What is the purpose of the random.choice function?
    It returns a random element from a non-empty sequence.
  13. What does the split method do?
    It splits a string into a list of substrings based on whitespace by default.
  14. What does the join method do?
    It concatenates a list of strings into a single string, with a specified separator.