CIS 2020 · Python for Everyone · Module 9 · Study guide

Module 9 review: strings, random numbers, dictionaries, and classes

This module finishes processing strings, then adds three new tools: random numbers for games and simulations, dictionaries for looking things up by name, and classes for making your own kinds of objects. The last example puts all of them together. Every example is short and prints its result, so run each one and check that the output matches what you predicted.

Section 4.8, continued

Processing Strings

In Module 8 you looped over a string to count characters and build new strings. This part answers different questions: where is a character, is it there at all, and does the whole string follow a rule?

Character test methods

Most string algorithms ask a question about one character at a time. Python has a method for each common question. Each one returns True or False.

Methods you can call on a single character (or a whole string)
MethodTrue whenExample
isdigit()Every character is a digit 0 to 9"7".isdigit() is True
isalpha()Every character is a letter"Q".isalpha() is True
isalnum()Every character is a letter or a digit"a1".isalnum() is True
isupper()The letters are all uppercase"HI".isupper() is True
islower()The letters are all lowercase"hi".islower() is True
isspace()Every character is whitespace" ".isspace() is True
for ch in "R2 d2!":
    print(ch, ch.isalpha(), ch.isdigit())

Run it and read the output line by line. The space and the exclamation point are neither letters nor digits, so both columns are False for them.

Finding all matches

To report where something appears, you need the position, so loop over the indexes instead of the characters.

word = "Mississippi"
for i in range(len(word)):
    if word[i] == "s":
        print("Found s at index", i)
Found s at index 2
Found s at index 3
Found s at index 5
Found s at index 6

Finding the first match

When you only need the first one, stop looking as soon as you find it. A for loop always visits every character, so this job uses a while loop with a boolean flag.

text = "Order 66 shipped"
found = False
position = 0

while not found and position < len(text):
    if text[position].isdigit():
        found = True
    else:
        position = position + 1

if found:
    print("First digit is", text[position], "at index", position)
else:
    print("No digits")
First digit is 6 at index 6

Two conditions keep the loop safe. not found stops it after the first match, and position < len(text) stops it at the end of the string so it never asks for an index that does not exist. Notice that position only moves forward when there is no match, so after the loop it still points at the match.

Finding the last match

Start at the last index, len(text) - 1, and walk backward.

filename = "report.final.txt"
found = False
position = len(filename) - 1

while not found and position >= 0:
    if filename[position] == ".":
        found = True
    else:
        position = position - 1

extension = ""
for i in range(position + 1, len(filename)):
    extension = extension + filename[i]

print("Last dot at index", position)
print("Extension:", extension)
Last dot at index 12
Extension: txt

Searching from the front would stop at the first dot, index 6, and report the extension as final.txt. The direction of the search matters.

Built in shortcuts: text.find("6") returns the index of the first match and filename.rfind(".") the last, or -1 if there is none. "@" in email answers yes or no. Learn the loops first, since they work for any test (like "first digit"), not just one exact character.

Validating a string

Validating means checking that every character follows the rule for its position. Assume the string is valid, then look for any character that breaks the rule.

pin = input("Choose a 4 digit PIN: ")

valid = len(pin) == 4
for ch in pin:
    if not ch.isdigit():
        valid = False

if valid:
    print("PIN saved")
else:
    print("A PIN must be exactly 4 digits")

Try 2468, 24a8, and 246. Only the first one passes.

When different positions have different rules, check the index. This one accepts a phone number written like (209)555-0142:

phone = "(209)555-0142"

valid = len(phone) == 13
i = 0
while valid and i < len(phone):
    ch = phone[i]
    if i == 0:
        valid = ch == "("
    elif i == 4:
        valid = ch == ")"
    elif i == 8:
        valid = ch == "-"
    else:
        valid = ch.isdigit()
    i = i + 1

print(phone, "valid:", valid)

Change one character, such as the dash to a space, and the program prints False. The loop stops at the first bad character, because there is no reason to keep checking once the answer is known.

Building a new string from the parts you want

phone = "(209)555-0142"
digits = ""
for ch in phone:
    if ch.isdigit():
        digits = digits + ch
print(digits)
2095550142
title = "my first python game"
result = ""
for i in range(len(title)):
    if i == 0 or title[i - 1] == " ":
        result = result + title[i].upper()
    else:
        result = result + title[i]
print(result)
My First Python Game

The second example capitalizes a letter when it is the first character or comes right after a space. It needs the index, because the rule depends on the character before the current one.

Common mistake: Strings cannot be changed in place. title[0] = "M" raises TypeError: 'str' object does not support item assignment. Build a new string instead, as above.

Section 4.9

Application: Random Numbers and Simulations

A simulation uses a program to imitate something in the real world, like rolling dice or flipping coins thousands of times. Random numbers supply the chance.

Getting random numbers

The tools live in the random module, so import it once at the top of the program.

import random

print(random.random())        # a float from 0 up to, but not including, 1
print(random.randint(1, 6))   # a whole number from 1 to 6, both ends included
print(random.uniform(1, 10))  # a float between 1 and 10
print(random.choice(["rock", "paper", "scissors"]))

Your output will differ every run. That is the point.

The random functions you will use most
CallGives
random.random()A float with 0 ≤ x < 1
random.randint(a, b)A whole number from a to b, including b
random.uniform(a, b)A float between a and b
random.choice(items)One item picked from a list or string
random.seed(n)Makes the same "random" sequence on every run, for testing

randint includes both ends; range does not. random.randint(1, 6) can return 6. range(1, 6) stops at 5. Mixing these up is the most common mistake in this section.

Simulating die tosses

import random

for roll in range(10):
    die = random.randint(1, 6)
    print(die, end=" ")
print()

A pair of dice is two separate calls added together. Do not use randint(2, 12): that makes 2 just as likely as 7, which real dice do not do.

die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print(die1, "+", die2, "=", die1 + die2)

Counting results over many trials

One roll tells you nothing. Thousands of rolls show the pattern. Combine the random number with a counting loop from Module 7.

import random

TRIES = 6000
sixes = 0
for i in range(TRIES):
    if random.randint(1, 6) == 6:
        sixes = sixes + 1

print("Sixes:", sixes, "out of", TRIES)
print("Fraction:", sixes / TRIES)

You will get close to 1000 sixes and a fraction near 0.167 (one sixth), but rarely exactly. More tries bring the result closer to the true probability.

A coin flip, and a loop that runs until something happens

import random

if random.random() < 0.5:
    print("Heads")
else:
    print("Tails")

# how many rolls until doubles?
rolls = 0
doubles = False
while not doubles:
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    rolls = rolls + 1
    print("Roll", rolls, ":", die1, die2)
    if die1 == die2:
        doubles = True
print("Doubles after", rolls, "rolls")

random.random() < 0.5 is true about half the time. Change 0.5 to 0.3 and the coin comes up heads about 30 percent of the time, which is how a simulation models an event with any probability.

The Monte Carlo method

Estimating pi by throwing random darts at a square A circle sits inside a square. Random points that land in the circle are hits; points in the corners outside the circle are misses. Four times the fraction of hits approximates pi. inside the circle: hit outside: miss pi is about 4 x hits / tries square: -1 to 1 circle: radius 1
The circle covers pi out of the square's 4 square units, so the fraction of random points that land inside approaches pi divided by 4.

The Monte Carlo method answers a question by running many random trials and measuring how often something happens. The classic example estimates pi. Throw random points at a square from −1 to 1 in each direction. A point is inside the circle of radius 1 when x * x + y * y <= 1.

import random

TRIES = 10000
hits = 0
for i in range(TRIES):
    x = random.uniform(-1, 1)
    y = random.uniform(-1, 1)
    if x * x + y * y <= 1:
        hits = hits + 1

pi_estimate = 4 * hits / TRIES
print("Estimate of pi:", pi_estimate)

Expect something like 3.13 or 3.15. Try TRIES = 100 and TRIES = 1000000 and compare how close each gets.

Testing a random program: put random.seed(1) right after the import. The numbers still look random, but they are the same on every run, so you can check whether a change to your code changed the result. Remove it when you are done. Computer random numbers are really pseudorandom: a formula that produces numbers that behave randomly.

Section 8.2

Dictionaries

A list finds items by position: item 0, item 1. A dictionary finds items by a name you choose, called a key.

A dictionary pairs each key with a value Three keys, Ana, Ben, and Cy, each connect to one value: 92, 78, and 85. Keys are unique; values may repeat. keys (unique)values "Ana""Ben""Cy" 927885 scores
scores["Ben"] looks up the key "Ben" and gives back its value, 78. There is no position number involved.

Creating a dictionary and looking up values

scores = {"Ana": 92, "Ben": 78, "Cy": 85}

print(scores["Ben"])     # 78
print(len(scores))       # 3 key and value pairs
print(scores)            # {'Ana': 92, 'Ben': 78, 'Cy': 85}

Curly braces hold the pairs. Each pair is written key: value, and pairs are separated by commas. An empty dictionary is {}.

A missing key is an error, so check first

print(scores["Dee"])
# KeyError: 'Dee'
name = input("Whose score? ")
if name in scores:
    print(name, "scored", scores[name])
else:
    print("No score for", name)

# get() returns a default instead of crashing
print(scores.get("Dee", 0))       # 0
print(scores.get("Ana", 0))       # 92

in checks the keys, not the values. "Ana" in scores is True, but 92 in scores is False.

Adding, changing, and removing

scores["Dee"] = 88       # new key: adds a pair
scores["Ben"] = 81       # existing key: replaces the value
print(scores)            # {'Ana': 92, 'Ben': 81, 'Cy': 85, 'Dee': 88}

removed = scores.pop("Cy")
print("Removed", removed)   # Removed 85
print(scores)               # {'Ana': 92, 'Ben': 81, 'Dee': 88}

The same statement, d[key] = value, either adds or replaces, depending on whether the key is already there. Keys are unique, so a dictionary can never hold two "Ben" entries. Values can repeat freely. pop() of a missing key raises KeyError, unless you give a default: scores.pop("Zed", None).

Looping over a dictionary

for name in scores:
    print(name, scores[name])

for name, score in scores.items():
    print(name, "has", score)

for name in sorted(scores):
    print(name)

print(list(scores.keys()))     # ['Ana', 'Ben', 'Dee']
print(list(scores.values()))   # [92, 81, 88]
print(sum(scores.values()) / len(scores))   # the class average

A plain for loop over a dictionary visits the keys, in the order they were added. items() gives each key with its value. sorted() gives the keys in alphabetical order.

Counting with a dictionary

This is the most useful dictionary pattern. Each new word starts at 0 thanks to get(), then goes up by one.

text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)
for word in sorted(counts):
    print(word, counts[word])
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
and 2
bat 1
cat 1
hat 1
the 3

The same pattern counts letters in a string (for ch in text) or totals of dice rolls, as in the last example.

Looking things up: a translator

slang = {"brb": "be right back", "idk": "I don't know", "ty": "thank you"}

message = "idk brb ty friend"
result = ""
for word in message.split():
    result = result + slang.get(word, word) + " "
print(result)
I don't know be right back thank you friend

slang.get(word, word) means "the translation if there is one, otherwise the word unchanged."

A dictionary as a record

student = {"name": "Maya", "id": 4417, "major": "CIS", "gpa": 3.6}
print(student["name"], "is a", student["major"], "major")
student["gpa"] = 3.7
List or dictionary?
ListDictionary
Written with[ ]{ }
Find an item byIts position, starting at 0Its key
Best whenOrder matters, or items have no namesYou look things up by name, ID, or word
Missing itemIndexErrorKeyError

Keys must be unchangeable. Strings, numbers, and tuples work as keys. A list cannot be a key (TypeError: unhashable type: 'list'), though a list can be a value: {"Ana": [92, 88, 95]}.

Section 9.2

Implementing a Simple Class

You have been using objects all along: strings, lists, and dictionaries all have methods. A class lets you design your own kind of object.

A class is a blueprint. It describes what data each object holds and what the object can do. An object (also called an instance) is one thing made from that blueprint. One class can make as many objects as you want, and each one keeps its own data.

One class, two objects The Tally class lists its methods reset, click, and get_value. Two objects, people and cars, are made from it, and each stores its own _value: 2 for people and 5 for cars. class Tally reset()click()get_value() the blueprint: methods Tally()Tally() people_value = 2 cars_value = 5 objects: each has its own data
Both objects share the same methods, but each one stores its own _value. Clicking people never changes cars.

A tally counter class

Think of the hand held clicker someone uses to count people at a door. It can be reset, clicked, and read.

class Tally:
    def reset(self):
        self._value = 0

    def click(self):
        self._value = self._value + 1

    def get_value(self):
        return self._value
The parts of a class
PartIn the exampleMeaning
Class nameTallyStarts with a capital letter, by convention
Methoddef click(self):A function that belongs to the class, indented inside it
selfself._valueThe particular object the method was called on
Instance variable_valueData stored inside each object. The underscore means "private: use the methods, not this variable directly"

Making and using objects

people = Tally()      # make an object: class name plus parentheses
people.reset()
people.click()
people.click()
print("People:", people.get_value())

cars = Tally()
cars.reset()
for i in range(5):
    cars.click()
print("Cars:", cars.get_value())
print("People:", people.get_value())
People: 2
Cars: 5
People: 2

When you write people.click(), Python runs click with self set to people. That is how one method can work on many different objects: self is whichever object is in front of the dot.

Setting starting values with a constructor

The class above has a trap: call click() on a new counter before reset() and you get AttributeError: 'Tally' object has no attribute '_value', because the instance variable does not exist yet. A special method named __init__ (two underscores on each side) runs automatically every time an object is made, so it is the right place to create instance variables.

class Tally:
    def __init__(self):
        self._value = 0

    def click(self):
        self._value = self._value + 1

    def undo(self):
        if self._value > 0:
            self._value = self._value - 1

    def reset(self):
        self._value = 0

    def get_value(self):
        return self._value

votes = Tally()          # __init__ runs here, so _value starts at 0
votes.click()
votes.click()
votes.undo()
votes.undo()
votes.undo()             # does nothing: the counter never goes below 0
print(votes.get_value()) # 0

undo() shows why programs use methods instead of changing _value directly. The method enforces a rule, never below zero, that code outside the class cannot accidentally break.

Methods with parameters

__init__ and other methods can take parameters after self. You pass them inside the parentheses when you call.

class Pet:
    def __init__(self, name):
        self._name = name
        self._hunger = 5

    def feed(self, snacks):
        self._hunger = self._hunger - snacks
        if self._hunger < 0:
            self._hunger = 0
        print(self._name, "ate", snacks, "snacks")

    def play(self):
        self._hunger = self._hunger + 2
        print(self._name, "played fetch")

    def status(self):
        if self._hunger == 0:
            return self._name + " is full"
        else:
            return self._name + " has hunger " + str(self._hunger)

rex = Pet("Rex")
mochi = Pet("Mochi")
rex.feed(3)
mochi.play()
print(rex.status())
print(mochi.status())
Rex ate 3 snacks
Mochi played fetch
Rex has hunger 2
Mochi has hunger 7

Notice Pet("Rex") passes one value, but __init__ lists two parameters. Python supplies self automatically; you supply everything after it.

Common class mistakes and the error they cause
MistakeWhat you see
Leaving self out of the method header, def click():TypeError: click() takes 0 positional arguments but 1 was given
Writing _value = _value + 1 without self.UnboundLocalError or NameError; without self. it is just a local variable
Forgetting the parentheses, people = Tallypeople is the class itself, not an object, and calls fail
Using an instance variable before it is setAttributeError; create it in __init__
Forgetting () on a method, print(people.get_value)Prints something like <bound method ...> instead of the number

Putting it together

A Die class, a simulation, and a dictionary

This program uses all four sections: a class, random numbers, a dictionary to count, and string building to draw a bar chart.

import random

class Die:
    def __init__(self, sides):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)

d6 = Die(6)
d4 = Die(4)

# roll the two dice 1000 times and count each total
totals = {}
for i in range(1000):
    total = d6.roll() + d4.roll()
    totals[total] = totals.get(total, 0) + 1

# print a bar chart, one star for every 10 rolls
for total in sorted(totals):
    bar = ""
    for star in range(totals[total] // 10):
        bar = bar + "*"
    print(total, bar, totals[total])

One run printed this:

2 **** 49
3 ********* 91
4 *********** 119
5 ***************** 178
6 *************** 152
7 ****************** 189
8 *********** 114
9 ******* 77
10 *** 31

Your numbers will differ, but the shape will not. A 6 sided die plus a 4 sided die can total anything from 2 to 10, and the middle totals 5, 6, and 7 come up far more often than 2 or 10 because there are more ways to make them: 4 ways each, against only 1 way (1 and 1) to make 2. The // is whole number division, so 49 rolls draw 4 stars.

Try changing it: make it Die(6) and Die(6) and see that 7 becomes the most common total. Add a get_sides() method. Store the counts in the class instead, so the Die remembers how often each face came up.

Quick check

If you remember only these

  • Loop over indexes when you need to know where a match is; loop over characters when you only need the characters.
  • To find the first match, use a while loop with a found flag and stop at the end of the string. To find the last match, start at len(text) - 1 and step backward.
  • To validate a string, assume it is valid, then set the flag to False on the first character that breaks the rule.
  • isdigit(), isalpha(), isupper(), and friends test characters. Strings cannot be changed in place; build a new one.
  • import random. random.randint(a, b) includes b; random.random() gives a float from 0 up to 1.
  • Roll two dice with two calls, not one bigger range. Many trials reveal the pattern; a single trial does not.
  • The Monte Carlo method estimates an answer by counting how often random trials succeed. random.seed() makes runs repeatable for testing.
  • A dictionary maps unique keys to values: d[key] looks up, d[key] = value adds or replaces, pop() removes.
  • A missing key raises KeyError. Check with in, or use get(key, default).
  • Looping over a dictionary gives the keys; items() gives key and value together. d[k] = d.get(k, 0) + 1 counts things.
  • A class is a blueprint; each object made from it has its own instance variables. Methods take self first, and self is the object before the dot.
  • __init__ runs automatically when an object is created, and is where instance variables get their starting values.