Title: Programming in Python
1Programming in Python
2Why programming?
- Real data quantity
- No duplication navigation bar
3Why Python?
- Simple to pick up
- Batteries Included
- Popular for webserver programming
4Who is using it?
- Google (various projects)
- NASA (several projects)
- NYSE (one of only three languages "on the floor")
- Industrial Light Magic (everything)
- Yahoo! (Yahoo mail groups)
- RealNetworks (function and load testing)
- RedHat (Linux installation tools)
- LLNL, Fermilab (steering scientific applications)
- Zope Corporation (content management)
- ObjectDomain (embedded Jython in UML tool)
- Alice project at CMU (accessible 3D graphics)
- More success stories at www.pythonology.com
5docs.python.org
- Tutorials
- Language reference
- Library reference
6Exercises
- For those with little programming experience.
- http//www.upriss.org.uk/python/PythonCourse.html
7Your First Program Hello World
- gtgtgt print 'Hello World'
- Hello World
8Your First Program Hello World
- gtgtgt print 'Hello World'
- Hello World
- Putting it in a file
- hello.py
- print 'Hello World'
- Running a file
- python hello.py
9Play around!
- On your machine, type 'python'
- Or use an webbased version at
- http//try-python.mired.org
10Writing Code
- Use a proper editor.
- Not notepad/word
- Syntax highlighting
- Vi or Emacs
- Notepad and similar
11Writing Readable Code
- Use Comments
- Lines starting with a hash are ignored
- and can be used to explain your code, e.g.,
- Here, we issue multiple prints because
- that is all we can do
- print 'one line'
- print 'another line'
- print 'I hope I can do more than print soon'
12Programming in Python
- Expressions
- Variables
- Operators
- Strings
- Control Flow
- Functions
- Datastructures
- File I/O
- Objects
13Expressions
- A binary truth statement
- false or true
- 0 or anything but 0
14Examples
Expression Truth
1 true
53425 true
0 false
15Expressions
- Consist of
- operands
- constant values
- variables
- function calls
-
- operators
- arithmetic (plus, minus, ) written as (,
-) - comparative (less than, greater than,
) written as (lt, gt) - logical (and, or, not) written as (and,
or, not)
16Examples
Expression Truth
1 true
53425 true
0 false
1 0 true
1 1 false
1 lt 2 true
1 2 false
not 1 false
not 0 true
17Variables
- Use names to hold values
- x 2
- y x 2
- Like mathematics
- In computer systems,
- variables are containers
- y x is an assignment, not a mathematical
relationship
18containers
19Variables
- myvalue 3.25
- message hello world
- Simple, eh?
20Variable types
- numbers
- x 3
- strings
- x some text
21Variable names
- Case sensitive
- x 3
- is not the same as
- X 3
- So
- x 3
- y X
- will not cause y to become equal to 3
22Operators
- Assignment
- i 1
- Arithmetic , -, , /
- i 1 1
- Comparison lt, gt, lt, gt, , !
- i lt 5
- Logical and, or, not
- i and j
- And more ...
23Expressions
- An expression can be broken down into operators
and operands - i lt 5
24Expressions
- but can be any combination of operands and
operators - a lt 3 and not b gt 5
25Expressions
- subparts are evaluated one by one
- (for a2, b6)
- a lt 3 and not b gt 5
- a lt 3 ?
- 2 lt 3 true
- true and not b gt 5
26Expression evaluation
- true and not b gt 5
- b gt 5 ?
- 6 gt 5 ? true
- true and not true
- not true? false
- true and false?
- false
27Expression evaluation
- what does not a lt b mean?
- (not a) lt b
- or
- not (a lt b)
- ?
28Expression evaluation
- when in doubt, add parentheses
- or lookup operator precedence on docs.python.org
29Strings
- 'this is a string'
- this is a string
- are identical. useful to avoid
- 'this isn't a string?'
30Example String Variables
- mymessage hello world
- print mymessage
31Multiline Strings
- triple quotes
- '''this
- is a
- string'''
32String Operations
- concatenation 'this is' 'a string'
- also 'these are now three strings ' 3
- strings consist of characters
- msg 'first second third'
- msg0
- msg04
- msg4
- msg-5
33Example
34Control Flow
- Basics
- If
- While
- For
- Exception Handling
35CF Branching
- If temperature gt 35
- print 'it is hot!'
- elif temperature lt 20
- print 'it is cold!'
- else
- print 'ah, nice!'
36That WhiteSpace Thing
- Indentation has meaning
- if a
- print 'hello'
- print 'world'
- Is not the same as
- if a
- print 'hello'
- print 'world'
37CF Loops
- i 0
- while i lt 10
- print 'not done'
- i i 1
- print 'done'
38CF Bounded Loops
for i in range(0,10) print 'not done' print
'done'
39CF Break
for i in range(0,10) print 'not done' if j
0 break print 'done'
40CF Continue
for i in range(0,10) if j 0 continue prin
t 'not done' print 'done'
41CF Exception Handling
try print 1 'st try' except print that
didn't work
42Functions
- Structure your programs
- def sayHello()
- print 'hello world'
- sayHello()
43Functions why?
- a 5
- b 3
- c 2
- d 4
- a lt (b c) and d lt (b c)
44Functions structured programming
- def firstfunc()
- return b c
- a lt firstfunc() and d lt firstfunc()
45Function Parameters
def say(something) print Im saying
something say(I'm getting tired of Hello World)
46Default parameters
def say(something 'NOT Hello World') print
something say()
47Function Return Value
- def max(a, b)
- if a gt b
- return a
- else
- return b
- print max(4, 6)
48Exercises
- Write a program that prints hello! 10 times
- Write a program that calculates how many years,
weeks and days have passed for a given variable
totaldays (disregard leap years) - Write a program that shows all divisors of a
given variable number - Write a program that calculates the first 10
fibonacci numbers
49Hints
- Divisors example
- c a / b will round down a number, so
- c 4/2 will give c2
- c 5/2 will also give c2
- Nesting
- you can nest control flow, e.g.,
- while a lt 5
- if b 0
50Using Python
51Using Python
52Using Python
53Datastructures
54DS List
- mylist one, two, three, four
- like looking up characters in a string
55Exercises
- Create a list of all students in this class and
print it - Write a function that takes two parameters a
list and a number. - Have the function print the element in the list
at index number
56DS More Lists
- Nested 1, 2, 2.5, 3
- Unordered 1, 3, 2
- Indexed mylist2
- Concatenation
- a 1, 2
- b 3
- c a b
57DS Tuple
- Immutable list
- (1, 2)
- More efficient than lists
58DS Dictionary
- List with not just values, but keyvalue pairs
- a name willem, cityamsterdam
- a0
- aname
59Exercise
- Create a dictionary of 10 countries and their
capitals. Write a function that returns a capital
when passed a country as parameter
60Advanced Topics
- Object Oriented Programming
- Libraries
- Servers
- Databases
61Object Oriented Programming
- structure readable and simple
objects
structured
functions
control flow
unstructured
62Intuition
- think of real world objects
- have properties
- can perform actions
63Example
- A car
- has a color
- can accelerate
64In programming
- actions are called methods (functions)
- properties are called attributes
65Objects and Classes
- classes are generic (types)
- objects are specific
66Example
- bike is a class
- my bike is an object
67Programming Classes
- class Car
- speed 0
- color blue
- def accelerate(self)
- self.speed self.speed 1
- def breakhard(self)
- self.speed 0
68Using Objects
- mycar Car()
- all objects of the same class share the same
methods - individual objects have individual state
- mycar red
69Inheritance
- Specialize classes
- a subclass inherits all methods and attributes
from its superclass, but can change/add these
70Example
- class Bike
- speed 0
- def slowdown(self)
- self.speed self.speed 10
- class Willemsbike(Bike)
- def slowdown(self)
- self.speed self.speed - 1
71Encapsulation
- self. only usable from within an object
- (we'll skip the rest)
72Import minimize namespace clutter
- import time
- time.ctime()
- time is a module (really just a file)
73In practice in this course
- 1. If you use libraries you need to use objects
- time.ctime()
- 2. sometimes you may create a subclass
- class MyHandler(BaseHTTPServer.BaseHTTPRequestHand
ler)
74Exercises
- Create the class fruit that has property color.
- Create the subclasses orange with orange color
and - mango with green color
- Create the class vehicle with
- properties speed, topspeed and acceleration
- methods accelerate and slowdown
- Create subclass truck with additional property
load - Create subclass car with higher topseed than
truck - Make sure you cannot accelerate beyond topspeed
75Libraries (or Batteries)
76Libraries (or Batteries)
77Libraries (or Batteries)
- http//docs.python.org/library/
78Files
- myfile open(bike.py, r)
- i 1
- data myfile.readline()
- while data
- print line 1 data
- data myfile.readline()
- i i 1
- myfile.close
79Strings
- strings are objects!
- len(str)
- str.upper()
- str.capitalize()
- str.isupper()
- docs.python.org
- dont need to be imported, always there
80telnetlib
- open a raw TCP connection to another server
- running at HOST, PORT
- remember that webservers by default use port 80
- t telnetlib.Telnet(www.google.com, 80)
- read, write and close like files
- t.write(hello)
- reply t.read_all()
81datetime
82time
- time.sleep(5)
- time.clock()
83winsound
- .Beep(freq, duration)
- .PlaySound(file, flags)
84turtle graphics
85httplib
- HTTPConnection.request()
- HTTPConnection.getresponse()
- HTTPResponse.read(amt)
86webbrowser
- webbrowser.open(url, new0, autoraise1)
87HTMLParser
88email
89import
- Just once more
- Dont forget to use import, so
- import telnetlib
- t telnetlib.Telnet(host, port)
90Packages Beyond Libraries
91Assignment 1.b
- Deadline Monday 8PM
- Write a program that downloads webpages
- Use telnetlib
- Write your own HTTP request
- Display raw output on screen or
- Better save HTML to a file
- (NB need only 10 lines (but more is allowed))
-
92Assignment 1.b
- Tip
- HTTP requests are of the form
- GET ltpathgt HTTP/1.0\n\n
93Assignment 1.b
- Optional Advanced Assignment
- Write your own webserver
- derive a subclass from BaseHttpServer
-
- Incredibly Difficult Assignment
- derive from TCPServer
94Assignment 1.a Deadline TODAY
- Email me your assignment, dont put it in the
directory - Send all files in one email
- to wdb_at_few.vu.nl
- with subject Assignment 1.a ltyournamegt
- NB do the same with 1.b before Monday 8PM