Programming in Python - PowerPoint PPT Presentation

1 / 94
About This Presentation
Title:

Programming in Python

Description:

Programming in Python Why programming? Real data: quantity No duplication: navigation bar Why Python? Simple to pick up Batteries Included Popular for ... – PowerPoint PPT presentation

Number of Views:348
Avg rating:3.0/5.0
Slides: 95
Provided by: netstream
Category:

less

Transcript and Presenter's Notes

Title: Programming in Python


1
Programming in Python
2
Why programming?
  • Real data quantity
  • No duplication navigation bar

3
Why Python?
  • Simple to pick up
  • Batteries Included
  • Popular for webserver programming

4
Who 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

5
docs.python.org
  • Tutorials
  • Language reference
  • Library reference

6
Exercises
  • For those with little programming experience.
  • http//www.upriss.org.uk/python/PythonCourse.html

7
Your First Program Hello World
  • gtgtgt print 'Hello World'
  • Hello World

8
Your 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

9
Play around!
  • On your machine, type 'python'
  • Or use an webbased version at
  • http//try-python.mired.org

10
Writing Code
  • Use a proper editor.
  • Not notepad/word
  • Syntax highlighting
  • Vi or Emacs
  • Notepad and similar

11
Writing 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'

12
Programming in Python
  • Expressions
  • Variables
  • Operators
  • Strings
  • Control Flow
  • Functions
  • Datastructures
  • File I/O
  • Objects

13
Expressions
  • A binary truth statement
  • false or true
  • 0 or anything but 0

14
Examples
Expression Truth
1 true
53425 true
0 false




15
Expressions
  • 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)

16
Examples
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
17
Variables
  • 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

18
containers
19
Variables
  • myvalue 3.25
  • message hello world
  • Simple, eh?

20
Variable types
  • numbers
  • x 3
  • strings
  • x some text

21
Variable 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

22
Operators
  • Assignment
  • i 1
  • Arithmetic , -, , /
  • i 1 1
  • Comparison lt, gt, lt, gt, , !
  • i lt 5
  • Logical and, or, not
  • i and j
  • And more ...

23
Expressions
  • An expression can be broken down into operators
    and operands
  • i lt 5

24
Expressions
  • but can be any combination of operands and
    operators
  • a lt 3 and not b gt 5

25
Expressions
  • 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

26
Expression 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

27
Expression evaluation
  • what does not a lt b mean?
  • (not a) lt b
  • or
  • not (a lt b)
  • ?

28
Expression evaluation
  • when in doubt, add parentheses
  • or lookup operator precedence on docs.python.org

29
Strings
  • 'this is a string'
  • this is a string
  • are identical. useful to avoid
  • 'this isn't a string?'

30
Example String Variables
  • mymessage hello world
  • print mymessage

31
Multiline Strings
  • triple quotes
  • '''this
  • is a
  • string'''

32
String 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

33
Example
  • x Hello
  • print x World

34
Control Flow
  • Basics
  • If
  • While
  • For
  • Exception Handling

35
CF Branching
  • If temperature gt 35
  • print 'it is hot!'
  • elif temperature lt 20
  • print 'it is cold!'
  • else
  • print 'ah, nice!'

36
That WhiteSpace Thing
  • Indentation has meaning
  • if a
  • print 'hello'
  • print 'world'
  • Is not the same as
  • if a
  • print 'hello'
  • print 'world'

37
CF Loops
  • i 0
  • while i lt 10
  • print 'not done'
  • i i 1
  • print 'done'

38
CF Bounded Loops
for i in range(0,10) print 'not done' print
'done'
39
CF Break
for i in range(0,10) print 'not done' if j
0 break print 'done'
40
CF Continue
for i in range(0,10) if j 0 continue prin
t 'not done' print 'done'
41
CF Exception Handling
try print 1 'st try' except print that
didn't work
42
Functions
  • Structure your programs
  • def sayHello()
  • print 'hello world'
  • sayHello()

43
Functions why?
  • a 5
  • b 3
  • c 2
  • d 4
  • a lt (b c) and d lt (b c)

44
Functions structured programming
  • def firstfunc()
  • return b c
  • a lt firstfunc() and d lt firstfunc()

45
Function Parameters
def say(something) print Im saying
something say(I'm getting tired of Hello World)
46
Default parameters
def say(something 'NOT Hello World') print
something say()
47
Function Return Value
  • def max(a, b)
  • if a gt b
  • return a
  • else
  • return b
  • print max(4, 6)

48
Exercises
  • 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

49
Hints
  • 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

50
Using Python
51
Using Python
52
Using Python
53
Datastructures
  • List
  • Tuple
  • Dictionary

54
DS List
  • mylist one, two, three, four
  • like looking up characters in a string

55
Exercises
  • 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

56
DS More Lists
  • Nested 1, 2, 2.5, 3
  • Unordered 1, 3, 2
  • Indexed mylist2
  • Concatenation
  • a 1, 2
  • b 3
  • c a b

57
DS Tuple
  • Immutable list
  • (1, 2)
  • More efficient than lists

58
DS Dictionary
  • List with not just values, but keyvalue pairs
  • a name willem, cityamsterdam
  • a0
  • aname

59
Exercise
  • Create a dictionary of 10 countries and their
    capitals. Write a function that returns a capital
    when passed a country as parameter

60
Advanced Topics
  • Object Oriented Programming
  • Libraries
  • Servers
  • Databases

61
Object Oriented Programming
  • structure readable and simple

objects
structured
functions
control flow
unstructured
62
Intuition
  • think of real world objects
  • have properties
  • can perform actions

63
Example
  • A car
  • has a color
  • can accelerate

64
In programming
  • actions are called methods (functions)
  • properties are called attributes

65
Objects and Classes
  • classes are generic (types)
  • objects are specific

66
Example
  • bike is a class
  • my bike is an object

67
Programming Classes
  • class Car
  • speed 0
  • color blue
  • def accelerate(self)
  • self.speed self.speed 1
  • def breakhard(self)
  • self.speed 0

68
Using Objects
  • mycar Car()
  • all objects of the same class share the same
    methods
  • individual objects have individual state
  • mycar red

69
Inheritance
  • Specialize classes
  • a subclass inherits all methods and attributes
    from its superclass, but can change/add these

70
Example
  • class Bike
  • speed 0
  • def slowdown(self)
  • self.speed self.speed 10
  • class Willemsbike(Bike)
  • def slowdown(self)
  • self.speed self.speed - 1

71
Encapsulation
  • self. only usable from within an object
  • (we'll skip the rest)

72
Import minimize namespace clutter
  • import time
  • time.ctime()
  • time is a module (really just a file)

73
In 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)

74
Exercises
  • 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

75
Libraries (or Batteries)
  • File access

76
Libraries (or Batteries)
  • Don't reinvent the wheel

77
Libraries (or Batteries)
  • http//docs.python.org/library/

78
Files
  • myfile open(bike.py, r)
  • i 1
  • data myfile.readline()
  • while data
  • print line 1 data
  • data myfile.readline()
  • i i 1
  • myfile.close

79
Strings
  • strings are objects!
  • len(str)
  • str.upper()
  • str.capitalize()
  • str.isupper()
  • docs.python.org
  • dont need to be imported, always there

80
telnetlib
  • 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()

81
datetime
  • datetime.date()

82
time
  • time.sleep(5)
  • time.clock()

83
winsound
  • .Beep(freq, duration)
  • .PlaySound(file, flags)

84
turtle graphics
85
httplib
  • HTTPConnection.request()
  • HTTPConnection.getresponse()
  • HTTPResponse.read(amt)

86
webbrowser
  • webbrowser.open(url, new0, autoraise1)

87
HTMLParser
88
email
89
import
  • Just once more
  • Dont forget to use import, so
  • import telnetlib
  • t telnetlib.Telnet(host, port)

90
Packages Beyond Libraries
91
Assignment 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))

92
Assignment 1.b
  • Tip
  • HTTP requests are of the form
  • GET ltpathgt HTTP/1.0\n\n

93
Assignment 1.b
  • Optional Advanced Assignment
  • Write your own webserver
  • derive a subclass from BaseHttpServer
  • Incredibly Difficult Assignment
  • derive from TCPServer

94
Assignment 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
Write a Comment
User Comments (0)
About PowerShow.com