118
Midterm Review Jim Eng [email protected]

SI 539 Midterm Review Jim Eng [email protected]. Midterm Exams One practical exam Come to Lab -- we hand out a programming problem -- must finish and hand

Embed Size (px)

Citation preview

SI 539

Midterm Review

Jim [email protected]

Midterm Exams•One practical exam

•Come to Lab -- we hand out a programming problem -- must finish and hand in within 2 hours -- open book, open notes, open laptop, can look at your old programming assignments, surf the web -- just no help from other people.

•One midterm -- classic stuff on paper / online

•Short answer, multiple choice, read code and tell what it does, very little code writing -- two pages of notes

What is the Course About?

•Learning about HTML, CSS - designing a web site’s look and feel

•Developing software driven web sites -- using Python and Google Application Engine

•Storing data in Databases

• ==== > Design of Complex Web Sites

Cloud Computinghttp://en.wikipedia.org/wiki/Cloud_computing

World-Scale Applications

• For world-scale applications - the servers must be distributed around the world

• But users must see a uniform “single image” - www.google.com

• Also the programmers cannot know the structure or grography of the servers - because this always changes

Programming in the Cloud

• Programmers operate in a controlled environment

• Programs do their programming thing - code + data

• A complex software framework manages getting the right code and data to/from the right servers.

• Software developers are unaware of geography

Post-Cloud ViewThe Cloud

...

My CodeMy Code

My CodeMy Code

Your CodeYour Code

My User

My User

Your User

HTTP - Request / Response

• The nature of the HTTP Request/Response cycle makes the cloud possible

• Since clients are not connected for very long - the cloud can be changed in between requests

• As long as the cloud “fakes” everything about the protocol - no one is the wiser..

• The cloud engineers at Google/Amazon/Yahoo are pretty clever.

HTTP Request / Response Cycle

http://www.oreilly.com/openbook/cgi/ch04_02.html

Browser

Web Server

HTTPRequest

HTTPResponse

Internet Explorer, FireFox, Safari, etc.

HTTP Request / Response Cycle

http://www.oreilly.com/openbook/cgi/ch04_02.html

Browser

Web Server

HTTPRequest

HTTPResponse

Internet Explorer, FireFox, Safari, etc.

GET /index.html

<head> .. </head><body><h1>Welcome to my application</h1> ....</body>

Post-Cloud ViewThe Cloud

My CodeMy Code

My CodeMy CodeYour CodeYour Code

My User

Post-Cloud ViewThe Cloud

My CodeMy Code

My CodeMy CodeYour CodeYour Code

My User

GETGET

Cloud Summary

• The cloud is the Internet plus computing that is “embedded” “inside” the network

• Companies like Google, Amazon, and Yahoo put servers all over the world

• Software runs on whichever server is most appropriate and data/code is moved around and the cloud can be reconfigured dynamically

HTMLHypertext Markup Language

HTML

•A way of marking up text to indicate that some text is different from other text

•We “tag” portions of the text to communicate meaning

<p>This is a paragraph with a <strong>loud</strong> word in

it.</p><p>And this is yet another

paragraph.</p>

The Web is a Young Technology

• Invented in early 1990’s

•Popular in 1994

•Robert Cailliau - coFounder of the World-Wide-Web

•http://en.wikipedia.org/wiki/Robert_Cailliau

Video: http://www.dr-chuck.com/media.php?id=70Captioned video: http://www.overstream.net/view.php?oid=eymoehn5r7ex

History of HTML / CSS• HTML 1.0 - 1993 - The Good Old Days - life was simple

• HTML 2.0 - 1995 - Some interesting layout features - abused

• CSS 1 - 1996

• HTML 3.2 - 1997

• HTML 4.0 - 1997 - Layout moving toward CSS

• CSS Level 2 - 1998

• HTML 4.01 - 1999 - What we use today

• XHTML 1.1 - 2001

• HTML 5 - 2009?

HTML has evolved a *lot* over the years - as

computers and networks have gotten faster.

http://en.wikipedia.org/wiki/HTML

Tim Berners-Lee

The Modern Era

•HTML is clean and simple

•There is no presentation in HTML - font, color, spacing, etc etc

•No use of tables except for tabular data

•CSS controls all layout, and look and feel

•Still a bit challenging - but converging

HTML Tag Basics

<h1>Hello World</h1>

<img src=”x.gif” />

Start tag End tag

Self-closing tag

Attribute

A self closing tag does not need a corresponding end

tag.

Tags “mark up” the HTML document. The tags are read and interpreted by the browser - but now

shown.

A Simple but Modern Page<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My Document Title</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> </body></html>

The Basic Outline<!DOCTYPE ... ><html> <head> <!-- Describes and sets up the document --> </head> <body> <!-- The document to be displayed --> </body></html>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>The Most Basic Web Page in the World</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><h1>The Most Basic Web Page in the World</h1><p>This is a very simple web page to get you started. Hopefully you will get to see how the markup that drives the page relates to the end result that you can see on screen.</p><p>This is another paragraph, by the way. Just to show how it works.</p> </body></html>

Begin Tag

End Tag

Attribute

Whitespace and end lines do not matter except in attributes.

Lists<body><h1>Lists - an introduction </h1><p>Here's a paragraph. A lovely, concise little paragraph.</p><p>Here comes another one, followed by a subheading.</p><h2>A subheading here</h2><p>And now for a list or two:</p><ul> <li>This is a bulleted list</li> <li>No order applied</li> <li>Just a bunch of points we want to make</li></ul><p>And here's an ordered list:</p><ol> <li>This is the first item</li> <li>Followed by this one</li> <li>And one more for luck</li></ol></body> With CSS layout - lists are lists.

Symbols<body> <p>Our current stock of craft knives &gt; our stock of spray mounts, but we still need to get both of them in as soon as possible!</p></body>

Images<h2>Welcome to our super-dooper Scuba site</h2><p><img src="divers-circle.jpg" width="200" height="162" alt="A circle of divers practice their skills" /></p><p>Glad you could drop in and share some air with us! You've passed your underwater navigation skills and successfully found your way to the start point - or in this case, our home page.</p>

In this case, the file divers-circle.jpg needs to be in the same directory as the file index.html.

<img src="divers-circle.jpg"

width="200" height="162"

alt="A circle of divers practice their skills"

/>

Begin Tag

End Tag

Begin TagBegin Tag

Show this when hovering, images are off, or for screen readers.

Which image to display

Optional - makes display quicker. Will resize to fit.

All information is communicated through the attributes of the img tag.

Paragraphs and Divs

<p>This is a paragraph.</p><div>This looks like a paragraph, but it's actually a div.</div><p>This is another paragraph.</p><div>This is another div.</div>

ThinkThink

div as Container<div> <p>This is a paragraph inside a div.</p> <p>So is this.</p></div>

<div id="header"> <h1>BubbleUnder.com</h1> <p>Diving club for the south-west UK</p></div>

“div” stands for “division” as it allows us to divide our page into parts or sections and then do something different with

each “section”.

The id attribute on the tag allows us to uniquely mark a

div in a document. The id tag is also useful for screen

readers.

Nested divs<div id="outer"> <div id="nested1"> <p>A paragraph inside the first nested div.</p> </div> <div id="nested2"> <p>A paragraph inside the second nested div.</p> </div></div> <!-- End of the outer div -->

Adding divs give us a “handle” to apply styling (CSS) to a block of text.

<body> <div id="header"> <h1><a href="index.htm">SI502</a></h1> <ul> <li><a href="books.htm">Books</a></li> <li><a href="topics.htm" >Topics</a></li> </ul> </div> <div id="bodycontent"> <h1>Networked Computing: About</h1> <p> This course is a survey course covering a broad range of technology topics at a high level. The course is aimed at students with no prior technical skills other than the general use of a computer. Really! </p> </div> </body>

Indicating Meaning in

the id tags on the <div>

Link Anatomy

<a href="about.html"> About Us </a>

Start Tag End Tag

Start TagStart TagStart TagStart Tag

Clickable Text

Where to go when link is clicked (an attribute).

We will make this pretty later with CSS.

Summary

•HTML has gone through many changes and evolutions

• It started clean and simple - then got ugly and nasty - now we are back to a clean and simple approach

•HTML Markup needs to focus on meaning - not formatting

•Formatting is handled using CSS - Cascading Style Sheets

CSSCascading Style Sheets

http://en.wikipedia.org/wiki/Cascading_Style_Sheets

Three ways to add style

• Inline Style - Add style information to a tag

•Embedded Style - Add style information to the document at the beginning

•External Style Sheet - Put all of your style in an external file

- preferred because two people can work independently

Inline Styles<p>A sentance.</p><p style="color: red; font-weight: bold;">The quick brown fox jumps over the lazy dog.</p><p>Another sentance.</p>

Embedded Style

External Style Sheets

ext.htm

ext.css

We have styled the site *after* the HTML was

prodced.

Anatomy of a CSS Rule

Selecting by tag name

body { font-family: Verdana, Helvetica, Arial, sans-serif; background-color: #e2edff; line-height: 125%; padding: 15px;}h1 { font-family: "Trebuchet MS", Helvetica, Arial, sans-serif; font-size: x-large;}li { font-size: small;}h2 { color: blue; font-size: medium; font-weight: normal;}p { font-size: small; color: navy;}

Styling a block by “id”

#tagline { font-style: italic; font-family: Times, serif; }

<div id="tagline"> <p>Diving club for the south-west UK - let's make a splash!</p> </div>

#tagline p { font-style: italic; font-family: Times, serif; }

or

Everything within block Paragraphs within block

id= identifies a *particular* block - only one in a document

<body> <div id="header"> <h1><a href="index.htm" class="selected">SI502</a></h1> <ul class="toolbar"> <li><a href="books.htm">Books</a></li> <li><a href="topics.htm" >Topics</a></li> </ul> </div> <div id="bodycontent"> <h1>Networked Computing: About</h1> <p> This course is a survey course covering a broad range of technology topics at a high level. The course is aimed at students with no prior technical skills other than the general use of a computer. Really! </p> </div> </body>

When building HTML, we add little

“handles” in the HTML to make it so

we can “style” areas of the document.

Selecting elements by class.fun { color: #339999; font-family: Georgia, Times, serif; letter-spacing: 0.05em;}

<p class="fun">A man walks into a bar; you would've thought he'd see it

coming!</p><p>Have a nice day.<p>

<p class=”fun”>More fun stuff</p>

Class can be used many times in a

document.

Nested selectors•p a {all <a> descendants of <p>}

•p > a {all <a> children of <p>}

•p * {all descendants of <p>}

•p > * > a {all <a> grandchildren of <p>}

• span#shriek {the one <span> that has a shriek id}

• span.omg {all <span> with an omg class}

• span[class=omg] {all <span> with an omg class}

• span + a { all <a> that are the same level as a <span> }

•p#spud > * > a.bungo[href=the_bad_place.html]

.toolbar li { display:inline; text-align:right;}#header ul { line-height: 1em; text-align: right;}#header h1 { font-size: 20px; font-weight: bold; float: left;}

Selecting by pseudo-class

a { font-weight: bold;}a:link { color: black;}a:visited { color: gray;}a:hover { text-decoration: none; color: white; background-color: navy;}a:active { color: aqua; background-color: navy;}

link - before a visit

visited - after it has been visited

hover - when your mouse is over it but you have not clicked

active - you have clicked it and you have not yet see the new page

Multiple tags with same styling

h1, h2, h3 { color: yellow; background-color: black;}

Adding style hooks

<div id=“wrap”><div id=“nav”><h1 /><ul><li id=“current”><span /></li><li><a><span /></a></li></ul></div><div id=“content”><h1 /></div></div>

Why ids?Why not just class everything?What if I need an <ul> in #content that needs to look different from the one in #nav ?

Adding style hooks

<div id=“wrap”><div id=“nav”><h1 /><ul><li id=“current”><span /></li><li><a><span /></a></li></ul></div><div id=“content”><h1 /></div></div>

Why ids?Why not just class everything?What if I need an <ul> in #content that needs to look different from the one in #nav ?

Everything is addressable!#nav h1#nav ul#nav li#nav li a#nav li a span#nav li#current#nav li#current span

What does “cascading” mean?

•http://css.maxdesign.com.au/selectutorial/advanced_cascade.htm

•Even simple web page could have three sylesheets applied

• Browser stylesheet

• Author’s stylesheet(s)

• User’s stylesheet

•Plus embedded rules and inline rules

•There can be conflicts

Resolving cascade conflicts

•http://css.maxdesign.com.au/selectutorial/advanced_conflict.htm

•Generally, author styles override user styles which override browser styles

• "!important" can be set on any declaration to override other styles

•Used by people with special needs (font size, colors, etc)

•Explore conflicts with Firebug

In conflict, who wins?

<body><p><span><a href=“#” id=“bingo”>

A link</a></span></p></body>

body{ color:gray}p {color:blue}span {color:green}a {color:fuchsia}span a {color:black}p span a {color:lime}body p span a {color:red}#bingo{display:none}

What color will “A link” be?

Two kinds of elements

• Inline - affects how text looks

•strong, span

•Block - Containers that can be laid out

•Paragraphs, etc

•CSS can change a tag from inline to block

#navigation li { display: inline;}

Inline Elements

•Flowed with other text

•span, em, strong, cite, a

•Inline tags can be nested as long as they match

•<span class=”important”><cite>Stuff</cite></span>

•Block can contain inline - but inline cannot contain block

Block Level Elements

•Starts on its own line - ends justification and starts a new block

•Can be a container for other elements

•h1 - h6, p, div, blockquote, ul, ol, form

•Blocks can contain other blocks

<div id=”content”> <p>One </p> <p>Two</p></div>

CSS Box Model• height and width properties size the block element

• margin properties define the space around the block element

• border properties define the borders around a a block element

• padding properties define the space between the element border and the element content

• background properties allow you to control the background color of an element, set an image as the background, repeat a background image vertically or horizontally, and position an image on a pagehttp://reference.sitepoint.com/css/boxmodel

The Box Model

.trapped { height: 100px; width: 200px; margin: 20px; border: 5px solid yellow; background:red; padding: 20px; font-family:Arial; color:orange; font-size:20px;}<p class=”trapped”>I am trapped in a glass case of emotion which is 100px high and 200px wide.</p>

115500

119900

114400

110000

5

2020

Border, padding, and margin are additive.

.trapped { height: 50px; width: 50px;}.trapped2 { height: 50px; width: 50px; border: 5px solid yellow; padding: 10px;}<p class="trapped">One</p><p class="trapped2">Two</p>

Emerging conventions & rules of thumb

•A series of items: p p p p p p

•A series of items with attributes: ul or ol

•A series of items with name-value pairs defining attributes: dl

•A series of items with more many attribute values: table

• Sections and, subsections: h1, h2, h3, ... h6, hr as separators

Fonts

body { font-family: "Trebuchet MS", Helvetica, Arial, sans-serif; font-size: x-large;}

Most Favorite Least Favorite

Fallback fonts: serif, sans-serif, monospace, cursive and fantasy.

Font Factors

font-size: xx-small x-small small

medium large

x-large xx-large

font-weight: bold or normal

font-style: normal or italic

text-decoration: none, underline, overline, or line-through

Color Names•W3C has listed 16 color names

that will validate with an HTML validator.

•The color names are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.

http://www.w3schools.com/html/html_colors.asp

Colors by the number...

#e2edffThree Numbers, Red, Green , and Blue - each from

00 - FF (Hexidecimal)

#ffffff = white#000000 = black#ff0000 = red#00ff00 = green#0000ff = blue

http://www.w3schools.com/css/css_colornames.aspWeb-safe

colors

Summary• CSS Layout is its own art and science

• CSS Basics are well established and well supported in all modern browsers

• The box model is pretty straightforward - and allows nice design within the standards with reasonable effort levels.

• Site layout and markup is further evolving - mostly to make it increasingly possible to support desktop like experiences on the web.

• These innovations will naturally cause incompatibilities - which make things interesting and frustrating at times.

Python

Patterns in programming - 1

•Sequential steps

•Conditional steps

•Repeated steps

•Stored and reused steps

add 300 grams of flour add 100 ml of milk add an egg if altitude > 2000: add an egg add 30 grams of salt while there are too many lumps: beat mixture with a fork open and add provided flavor packet

Patterns in programming - 2

•Input

•Processing

•Output

usf = input("Enter the US Floor Number: ") wf = usf - 1 print "Non-US Floor Number is ",wf

print "Your guess is", guess answer = 42 if guess < answer : print "Your guess is too low" if guess == answer : print "Congratulations!" if guess > answer : print "Your guess is too high"

Logical expressions

True or false?

print “Bad print “Bad guess”guess”

print “Bad print “Bad guess”guess”

truetrue falsefalse

answer = 42answer = 42answer = 42answer = 42

print “Good print “Good Guess”Guess”

print “Good print “Good Guess”Guess”

guess == answer

print "Your guess is", guess answer = 42 if guess == answer : print "Congratulations!" else: if guess < answer : print "Your guess is too low" else: print "Your guess is too high"

Nested if-else statement

truetrue falsefalse

answer = 42answer = 42answer = 42answer = 42

print print “Congratulations“Congratulations

””

print print “Congratulations“Congratulations

””

guess == answer

print “Too High”print “Too High”print “Too High”print “Too High”

truetrue falsefalse

print “Too low”print “Too low”print “Too low”print “Too low”

guess < answer

print "Your guess is", guess answer = 42 if guess == answer : print "Congratulations!" elif guess < answer : print "Your guess is too low" else: print "Your guess is too high"

print “Congrats”print “Congrats”print “Congrats”print “Congrats”

truetrue

falsefalse

answer = 42answer = 42answer = 42answer = 42

guess == answer

truetrue

falsefalse

guess < answer print “Too low”print “Too low”print “Too low”print “Too low”

print “Too high”print “Too high”print “Too high”print “Too high”

Variables

•A way of assigning a name for an area of memory

•A way of saving data temporarily

•Called a “variable” because contents can change

•Value of variable remains the same until it is changed or discarded

Assignment statements

•Sets the value of a variable

•Assign the value 42 into the variable named ‘answer’

•Assignment operator (‘=’) not equality operator (‘==’)

answer = 42

guess == answer

Expressions

•(usf - 1) is an expression

•(usf - 1) means retrieve the value of usf and subtract one from it

•oh, yeah, and save it in the variable wf

wf = usf - 1

Variable names in Python

•Must start with a letter or underscore

•Consist of letters, underscores, numbers

•Case-sensitive (myVariable is not the same as myvariable)

•Choose meaningful, mnemonic variable names

Reserved wordsand del from not whileas elif global or withassert else if pass yieldbreak except import printclass exec in raisecontinue finally is returndef for lambda try

•Have special meanings

•Cannot be used as variable names, function names, etc

Constants

•Values that never change

usf = input("Enter the US Floor Number: ") wf = usf - 1 print "Non-US Floor Number is ",wf

Strings

•Assignment -- msg = "Hello World!"

•Array notation to select characters -- msg[6], msg[6:11], msg[:5], msg[6:]

•String methods -- msg.find('W')

•String concatenation

>>> txt = "guess=25" >>> print txt[0] g >>> print txt[1] u >>> print txt[2:4] es >>> print txt[2:5] ess >>> print txt[:5] guess >>> print txt[6:] 25 >>>

>>> pos = txt.find("=") >>> print pos 5 >>> print type(pos) <type 'int'> >>> print txt[:pos] guess >>> print txt[(pos + 1):] 25 >>> >>> think = "happy" + " " + "thoughts" >>> print think happy thoughts >>>

>>> print txt.endswith("2")False>>> print txt.endswith("25")True>>> print txt.startswith("g")True>>> print txt.startswith("go")False>>> print txt.upper()GUESS=25>>> txt = txt.upper()>>> print txtGUESS=25>>> print txt.lower()guess=25>>>

>>> txt = "abc" + "def" >>> print txt abcdef >>> num = 36 + 6 >>> print num 42 >>> huh = "abc" + 6 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> >>> huh = "abc" + str(6) >>> print huh abc6 >>>

>>> dir('abc')['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>>

>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc')<type 'str'>>>>

Lists are OK•We can use them to keep things in order

•We can add things to lists -- pals.append('Joe'), pals.insert(3,'Aaron')

•We can sort them -- pals.sort()

•We can directly access individual items -- pals[2]

•We can iterate through the items -- for pal in pals:

•We can concatenate lists -- list3 = list1 + list2

>>> pals = list() >>> pals.append("Glenn") >>> pals.append("Sally") >>> pals.append("Joe") >>> print pals ['Glenn', 'Sally', 'Joe'] >>> print type(pals) <type 'list'> >>> print len(pals) 3 >>> print pals[2] Joe >>> pals[2] = 'Joseph'>>> print pals[2] Joseph >>>

>>> num = 1>>> for pal in pals: ... print num, ") ", pal ... num = num + 1 ... 1 ) Glenn 2 ) Sally 3 ) Joseph >>>

>>> pals.sort()>>> num = 1>>> for pal in pals:... print num, ") ", pal... num = num + 1... 1 ) Glenn2 ) Joseph3 ) Sally>>>

>>> list2 = list()>>> list2.append("Jennifer")>>> list2.append("Jack")>>> list2['Jennifer', 'Jack']>>> print list2['Jennifer', 'Jack']>>> print pals['Glenn', 'Joseph', 'Sally', 'Aaron', 'Erin', 'Michele']>>> new_list = pals + list2>>> print new_list['Glenn', 'Joseph', 'Sally', 'Aaron', 'Erin', 'Michele', 'Jennifer', 'Jack']>>>

>>> def print_list(list):... num = 1... for item in list:... print num, ") ", item... num = num + 1... >>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally>>>

>>> pals = list()>>> pals.append('a')>>> pals.append('x')>>> pals.append('b')>>> pals.append('y')>>> pals.append('c')>>> pals.append('z')>>> print pals['a', 'x', 'b', 'y', 'c', 'z']>>> dir(pals)['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']>>>

>>> print len(pals)6>>> print type(pals)<type 'list'>>>> print pals.count('b')1>>> print pals.index('b')2>>>

Functions

•Defining functions -- syntax, parameters, returns

• Invoking functions -- syntax, parameters returns

•Variables inside functions

>>> def foot_label(num):... label = "feet"... if(num == 1):... label = "foot"... return label... >>> def inch_label(num):... label = "inches"... if(num == 1):... label = "inch"... return label... >>>

>>> def print_feet(inches_in):... feet = inches_in / 12... inches = inches_in % 12... msg = str(inches_in) ... msg = msg + " inches equals " + str(feet) ... msg = msg + " " + foot_label(feet)... if(inches > 0):... msg = msg + " and " + str(inches) ... msg = msg + " " + inch_label(inches)... print msg... >>>

>>> print_feet(12000)12000 inches equals 1000 feet>>> print_feet(nums[1])12000 inches equals 1000 feet>>> for num in nums:... print_feet(num)... 12 inches equals 1 foot12000 inches equals 1000 feet12345 inches equals 1028 feet and 9 inches13000 inches equals 1083 feet and 4 inches15000 inches equals 1250 feet>>>

Dictionaries

•We can use a dictionary to associate keys and values

•We can describe an individual by its attributes

•We can iterate over the keys and access the values

>>> pal = dict()>>>>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-1234'>>>>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}>>>

>>> print pal['phone']734-555-1234>>>>>> print pal['age']Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'age'>>>

>>> print pal.get('age', 'Age not available')Age not available>>>>>> print pal.get('phone', 'Phone not available')734-555-1234>>>>>> print pal.get('age', 21)21>>>

>>> dir(pal)[..., 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>>

>>> pal.keys()['phone', 'last', 'email', 'first']>>> pal.values()['734-555-1234', 'Silverio', '[email protected]', 'Gonzalo']>>> pal.has_key('phone')True>>> pal.has_key('age')False>>> pal.items()[('phone', '734-555-1234'), ('last', 'Silverio'), ('email', '[email protected]'), ('first', 'Gonzalo')]>>>

>>> pals = list()>>> pal = dict()>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-1234'>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}>>> pals.append(pal)>>>

>>> pal = dict()>>> print pal{}>>> pal['first'] = 'Jim'>>> pal['last'] = 'Eng'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-4123'>>> pals.append(pal)>>> print pals[{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}, {'phone': '734-555-4123', 'last': 'Eng', 'email': '[email protected]', 'first': 'Jim'}]>>>

>>> nk = " not known">>> for pal in pals:... for key in keys:... print key, ": ", pal.get(key, key + nk)... print " ---- "... first : Gonzalolast : Silveriophone : 734-555-1234email : [email protected] : age not knownbirthday : birthday not known ---- first : Jimlast : Engphone : 734-555-4123email : [email protected] : age not knownbirthday : birthday not known ---- >>>

>>> person = dict()>>> for key in keys:... val = raw_input(key + ": ")... person[key] = val... first: Denzellast: Washingtonphone: 323-555-6789email: [email protected]: 54birthday: Dec 28>>> print person{'last': 'Washington', 'age': '54', 'phone': "323-555-6789", 'birthday': 'Dec 28', 'email': '[email protected]', 'first': 'Denzel'}>>>

Try ... except

•We can "try" to execute parts of a program where errors might cause the program to crash

•We can "catch" errors and handle them gracefully

>>> try:... print int('42')... except:... print 'oops'... 42>>> try:... print int('forty-two')... except:... print 'oops'... oops

>>> def safeint(val):... try:... print int(val)... except:... print 'oops'... >>> safeint(42)42>>> safeint(42.5)42>>> safeint('42')42>>> safeint('forty-two')oops>>>

Classes and Objects

•We can define classes and then create instances of our classes

•A class encapsulates data and methods related to a particular type of object

•An instance of a class is an object

•We invoke methods on objects

•Sometimes we pass an object as a parameter to a function

class Simple(): num = 0 def incr(self): self.num = self.num + 1 return self.num def square(self): self.num = self.num * self.num return self.num def decr(self): self.num = self.num - 1 return self.num

x = Simple()print dir(x)print "x.num == ", x.numprint "x.incr()",x.incr()print "x.incr()",x.incr)print "x.decr()",x.dec()print "x.incr()",x.incr()print "x.square()",x.square()print "x.decr()",x.decr()print type(x)

$ python simple.py ['__doc__', '__module__', 'decr', 'incr', 'num', 'square']x.num == 0x.incr() 1x.incr() 2x.decr() 1x.incr() 2x.square() 4x.decr() 3<type 'instance'>

Midterm exams

•Written exam in lecture -- Wednesday 9 a.m.

•Practical exam -- in lab

•Tuesday 4-6 p.m.

•Thursday 4-6 p.m.