oct 7
The files I made from today's class are attached.
At this point, with
- lists, strings, numbers
- loops
- functions, return values, tests
- conditionals
- input and output to both command line and files
- graphics via Zelle's package
you have a lot under your belt, and have the
programming 'power' do to lots of stuff.
So: midterm programming project
- Proposal idea(s) due next week; your choice of project.
- See assignments page for details.
- See http://projecteuler.net for some math-ish ideas.
- Other ideas: a physics simulation, a game of some sort, an elaboration of an earlier assignment.
Today: continue discussion of "if" and conditionals; work out some exercises in class.
'if', 'while', and all that
So what does this do ?
for x in range(20):
if (x < 10) and (x > 5):
print "x is between 5 and 10"
else:
print "."
How about this ?
numbers = [1,2,10,20,50,80]
while numbers:
x = numbers.pop(0)
print x
"while" is often a good way to implement a loop;
do some stuff repeatedly until a condition is false.
Just make sure that the condition changes eventually,
or that you leave the function, otherwise you'll be
stuck in the loop.
# This is bad
while True:
print "hi there\n"
An example of a good use of "while True:" could
be returning validated user input, using "return"
to exit the loop, and repeating until valid input
is seen.
exercises in class
1 Write a program that finds the smallest number that is divisible by 1 through 20.
- Approach?
- What loops are needed?
- What branches? Where?
2 Truth table exercise from Tues notes
try, catch
try:
x = int(raw_input("What is x? "))
except ValueError:
print "You must enter a number."
This is like an (if: ... else: ...) construct,
but for system errors. See the error happen
to figure out what to put after the "except" part.
Sometimes this is called "throwing" and exception and "catching" it.
Class exercise: write the "while True:" validated user input described above
with an exception handler.