WARMUP
Bananagrams is a word game.
There is a large pool of unrevealed letters, and each player initially draws 15.
They then try to form words, as if they were playing on their own Scrabble board. However, they can reform the words any time they like.
Once a players uses their pile of tilestr, they declare ‘Peel’, and all players draw another tile. Any player may declare ‘Dump’ and return any tile to the unrevealed pile and draw two new tiles.
When the unrevealed pile has fewer letters than players, the next player to use all their tiles may declare ‘Bananas’. If their words are all correct, they win. If not, they lose, their tiles are returned to the unrevealed pile, and play resumes.
HW Review
What did people have the most trouble figuring out? ask random
Programming
Thing big: what was this homework about? ask random
Command Line Input
Recall how we use python scripts from the console:
$ ./somescript.py [...optional arguments]
Inside the script, we can access these optional arguments in a special way:
#!/usr/bin/env python3
__author__ = 'cap10'
## called as $ ./input_cl.py some arg u ments 1 2 3
import sys
print(sys.argv)
## prints ['input_cl.py', 'some', 'arg', 'u', 'ments', '1', '2', '3']
(note: when running with PyCharm, I had to edit the run configuration to pass arguments. This is the input field below the script name)
Recall:
- the script name itself is the first argument
- the rest of the arguments are string values, even though we provided some numbers
When we just need to provide a series of arguments in a fixed format, this approach will do nicely. However, if we want to use our Python script more like a command line utility like ls
, we should be able to support a more complicated syntax:
$ somecommand -xvf --target="thing" 1 2 3
Writing a parser for this is quite fiddly. Fortunately, there is a built in module for addressing this problem, argparse
:
#!/usr/bin/env python3
__author__ = 'cap10'
## called as $ ./input_cl2.py -v 1 --somearg "five"
import argparse
parser = argparse.ArgumentParser(description='demonstration.')
parser.add_argument('-v', type=int, dest='theint',
help='an integer')
parser.add_argument('--somearg', dest='thestring', type=str,
help='a string')
parser.add_argument('-u', dest='uncalled', type=float, default=42.0,
help='an optional arg')
args = parser.parse_args()
print("\n", args, args.thestring, args.theint)
Still complex, but not nearly as complex as writing it yourself. And argparse
automatically handles providing a useful help option and will complain sensibly when offered incorrect arguments.
User Input
Often, we want to interact with a program, like for example the Python REPL. Here is a simple input-output loop:
__author__ = 'cap10'
something = input("enter something:")
while something != "stop":
print(something)
something = input("enter something, 'stop' to stop:")
anumber = None
while anumber != -1:
try:
anumber = int(input("enter an integer, -1 to stop:"))
except (TypeError, ValueError) as err:
print(err.args[0])
else:
print("success", anumber)
We use the input(\...)
command to prompt the user for input, but must be careful as what is submitted is always a string in this version.
File Input
The other typical input case is that we have a file of data which we want to use rather than directly coding which particular values we want to evaluate with our programs.
__author__ = 'cap10'
myfile = open("filename.csv",'r') # 'r' is for read
print("first pass\n")
for line in myfile:
print(line)
print("second pass\n")
for line in myfile:
print(line)
myfile.seek(0) # need to reset position in file
print("works this time?\n")
for line in myfile:
print(line.rstrip())
myfile.close()
print("\nnow with csv:")
import csv
with open("filename.csv",'r') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
for row in reader:
print(row)
HOMEWORK
Write a program random_pi.py
that:
Receiving a seed and sample size, generates that many random numbers, uniformly sampled on 0 to 1.
Using those random numbers, estimate the value of pi
by the circle-area method and then by the sphere-volume method.
You program should behave like:
$ ./random_pi.py 0 10000
circle-area pi: ...
sphere-volume pi: ...