Housekeeping There will be a quiz on the basics of functions on Tues and Wed, depending on your block.
Let's shoot for the end of the week for to_the_moon.py
and string_play.py
. The first is a very simple exercise
in input and output and the second can be done by using Python's
string methods pretty much "straight out of the bottle."
The random
Library
This is the last item in the boss statements chapter. It's fabulous for making games and for doing stochastic simulation when combined with looping. We will do a brief tour of some of its services
Shuffling a List
Random Sampling from a List
Flipping a Coin
Magic 8 Ball
Here is a list with its replies.
replies = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "It is certain.", "It is decidedly so."]
Generating Pseudorandom Integers
Roll a pair of dice. Roll an exotic die from an RPG, say 20-sided
Generating Uniform Variates
Iterables and Definite Repetition
Hummingbird iterating through a collection of flowers
for flower in inflorensce:
suck_nectar(flower)
pollinate(flower)
What is an iterable? For now,
think this way. Iterables are "food" for for
loops. Iterables contain an object called an
iterator, which causes the elements to be visited
in succession to a for
loop to act upon. Here is a field
guide to iterators for our favorite types. One nice thing
about iterators: they do not change the collection they are walking
through.
- strings This iterator walks through a string one character at a time in index order.
- lists and tuples Their iterators walk through one element at a time in index order.
- sets The iterator walks through the set in no particular order.
- dictionaries The iterator walks the keys of a dictionary one key at a time in no particular order.
- file objects The iterator walks through a file one line at a time.
Here are some other iterables.
- range objects
- dictionary_keys object
- dictionary_values object
We will do tons of examples.
enumerate
and reversed
are very handy
for altering the behavior of iterators.