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.
More operators
Multiline strings
Lists
Dictionaries
Functions that return values
Randomization
split and join
Before we write our own yapping program, we’ll get in the mood to chat, by spending some time chatting with Python itself.
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"""
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
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'
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.
You might have noticed Python has a lot of operators. Here are a few:
| Operators | Description |
|---|---|
| + – * / // % ** | addition, subtraction, division, floorDivision, remainder, exponentiation |
| < <= == != >= > | lessThan, lessThanOrEqual, equalTo, notEqualTo, greaterThanOrEqual, greaterThan |
| and or not | and, or, not |
Try some on your own!
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'
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.
Now it’s your turn. Here are some ideas for you to extend the activities above:
template with a variable templates whose value is a list of strings.random_paragraph so that when called, returns a string consisting of between 3 and 8 random sentences, each of which comes from a randomly selected template.We’re making progress with Python. Continue with your reading:
We’ve covered:
random.choicesplit and joinHere 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.
python (or python3) with no arguments? 5 * 3, 5 > 3, and 5 == 3? 21 / 5, 21 // 5, and 21 % 5? ''' or """.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? s == t, (b) s.startswith(t), (c) s.endswith(t), (d) t in s.a? a[2].pets is the list ["Cinnamon", "Sundae", "Donut", "Brownie", "Cookie", "Benedict The Sixteenth"], how to we get the sublist ["Sundae", "Donut", "Brownie"]? pets[1:4].s is a list, what is the difference between s + ["dog"] and s.append("dog")? {"Colombia": "Bogotá", "Brazil": "Brasília", "Argentina": "Buenos Aires"}.d[k] where d is a dictionary and k is a key that is not in the dictionary? KeyError.def is_positive(n):
return n > 0random.choice function? split method do? join method do?