Intro to
Programming
with Python

Fall 2010
course
navigation

oct 7

The files I made from today's class are attached.

At this point, with
you have a lot under your belt, and have the programming 'power' do to lots of stuff.
So: midterm programming project
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.
2 Truth table exercise from Tues notes
3 Something from http://projecteuler.net

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.
http://cs.marlboro.edu/ courses/ fall2010/python/ notes/ oct_7
last modified Thursday October 7 2010 10:02 am EDT

attachments [paper clip]

     name last modified size
   and_or_truth_table.py Oct 7 2010 10:02 am 310B    class.py Oct 7 2010 10:02 am 189B    find_divisible.py Oct 7 2010 10:02 am 1.46kB    input.py Oct 7 2010 10:02 am 226B