Intro to
Programming
(with Python)

Fall 2016
course
navigation

Oct 6

homework

First, a discussion the functions homework, both some of my examples and looking at your submissions.

finish discussion of booleans

After finishing our class notes from last time we'll continue with these.

the while loop

x = 10 while x > 1: print "x is", x x = x - 1

coding truth tables

One of the assignments for next week is like this.
Now let's write in class a program to loop through assignments of (True, False) to (x,y) to see which (if any) of these are related.
(We talked about this in class on Tuesday - now let's write some code that does that, rather than doing it by hand on the board.)
(not x) and (not y) # which of these are the same ? not (x and y) not (x or y) (not x) or (not y)
Here's the code that I showed in class to do this :
formatline = " {:6} {:6} {:16} {:16} " print formatline.format('a', 'b', 'not (a and b)', '(not a) or (not b)') print formatline.format('-'*6, '-'*6, '-'*16, '-'*16) for a in (True, False): for b in (True, False): print formatline.format(str(a), str(b), str(not (a and b)), str((not a) or (not b)) )
which outputs this :
a b not (a and b) (not a) or (not b) ------ ------ ---------------- ---------------- True True False False True False True True False True True True False False True True

tidbits

The end of Tuesday's notes mentions a few more obscure corners of conditionals (ternary one line forms, and "shortcut" expressions - I'll point at them briefly for those who are interested, and then let any of you who are interested explore them yourselves.

try, catch

Discuss errors and how to handle them in Python :
try: x = int(raw_input("What is x? ")) except ValueError: print "You must enter a number."
This is like an (if: ... else: ...) conditional construct, but here the branch happens when a python error takes place. We say that the error is "caught" in the code, instead being printed out and stopping the program.
To figure out what to put after the "except" part, do something at the interactive prompt to make the error happen.
Sometimes this is called "throwing" and exception and "catching" it.
Class exercise : re-use the try/except code above as the basis for a function get_integer() which asks the user for an integer, and then keeps asking until an integer is actually typed.

practice

Work some problems in class. While they're pretty math-geeky, this site has many good programming problems :
projecteuler.net
A few good ones to start:

http://cs.marlboro.edu/ courses/ fall2016/python/ notes/ Oct_6
last modified Thursday October 6 2016 1:23 pm EDT