Docsity

Programação avancada em Python, Notas de estudo de Informática

Pré-visualização parcial do texto

Baixe Programação avancada em Python e outras Notas de estudo em PDF para Informática, somente na Docsity!

Advanced Python Programming

David M. Beazley

Department of Computer Science

University of Chicago

[email protected]

O’Reilly Open Source Conference

July 17, 2000

O’Reilly OSCON 2000, Advanced Python Programming, Slide 1

July 17, 2000, [email protected]

Overview

Advanced Programming Topics in Python

A brief introduction to PythonWorking with the filesystem.Operating system interfacesProgramming with ThreadsNetwork programmingDatabase interfacesRestricted executionExtensions in C.

This is primarily a tour of the Python library

Everything covered is part of the standard Python distribution.Goal is to highlight many of Python’s capabilities.

O’Reilly OSCON 2000, Advanced Python Programming, Slide 2

July 17, 2000, [email protected]

A Very Brief Tour of Python O’Reilly OSCON 2000, Advanced Python Programming, Slide 4

July 17, 2000, [email protected]

Starting and Stopping Python

Unix

unix %

python Python 1.5.2 (#1, Sep 19 1999, 16:29:25)

[GCC 2.7.2.3] on linux

Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam>>>

On Windows and Macintosh

Python is launched as an application.An interpreter window will appear and you will see the prompt.

Program Termination

Programs run until EOF is reached.Type Control-D or Control-Z at the interactive prompt.Or type^ raise SystemExit

O’Reilly OSCON 2000, Advanced Python Programming, Slide 5

July 17, 2000, [email protected]

Variables and Expressions

Expressions

Standard mathematical operators work like other languages:^ 3 + 53 + (5*4)3 ** 2’Hello’ + ’World’

Variable assignment

a = 4 << 3b = a * 4.5c = (a+b)/2.5a = "Hello World" Variables are dynamically typed (No explicit typing, types may change during execution).Variables are just names for an object. Not tied to a memory location like in C.

O’Reilly OSCON 2000, Advanced Python Programming, Slide 7

July 17, 2000, [email protected]

Conditionals

if-else

Compute maximum (z) of a and bif a < b:

z = b else:

z = a

The pass statement

if a < b:

pass

Do nothing

else:

z = a

Notes:

Indentation used to denote bodies.pass used to denote an empty body.There is no ’?:’ operator.

O’Reilly OSCON 2000, Advanced Python Programming, Slide 8

July 17, 2000, [email protected]

Basic Types (Numbers and Strings)

Numbers

a = 3

Integer

b = 4.

Floating point

c = 517288833333L

Long integer (arbitrary precision)

d = 4 + 3j

Complex (imaginary) number

Strings

a = ’Hello’

Single quotes

b = "World"

Double quotes

c = "Bob said ’hey there.’"

A mix of both

d = ’’’A triple quoted stringcan span multiple lineslike this’’’e = """Also works for double quotes"""

O’Reilly OSCON 2000, Advanced Python Programming, Slide 10

July 17, 2000, [email protected]

Basic Types (Lists)

Lists of Arbitrary Objects

a = [2, 3, 4]

A list of integers

b = [2, 7, 3.5, "Hello"]

A mixed list

c = []

An empty list

d = [2, [a,b]]

A list containing a list

e = a + b

Join two lists

List Manipulation

x = a[1]

Get 2nd element (0 is first)

y = b[1:3]

Return a sublist

z = d[1][0][2]

Nested lists

b[0] = 42

Change an element

O’Reilly OSCON 2000, Advanced Python Programming, Slide 11

July 17, 2000, [email protected]

Basic Types (Dictionaries)

Dictionaries (Associative Arrays)

a = { }

An empty dictionary

b = { ’x’: 3, ’y’: 4 }c = { ’uid’: 105,

’login’: ’beazley’,’name’ : ’David Beazley’ }

Dictionary Access

u = c[’uid’]

Get an element

c[’shell’] = "/bin/sh"

Set an element

if c.has_key("directory"):

Check for presence of an member

d = c[’directory’] else:

d = None d = c.get("directory",None)

Same thing, more compact

O’Reilly OSCON 2000, Advanced Python Programming, Slide 13

July 17, 2000, [email protected]

Loops

The while statement

while a < b:

Do somethinga = a + 1

The for statement (loops over members of a sequence)

for i in [3, 4, 10, 25]:

print i

Print characters one at a timefor c in "Hello World":

print c

Loop over a range of numbersfor i in range(0,100):

print i

O’Reilly OSCON 2000, Advanced Python Programming, Slide 14

July 17, 2000, [email protected]

Classes

The class statement

class Account:

def init(self, initial):

self.balance = initial def deposit(self, amt):

self.balance = self.balance + amt def withdraw(self,amt):

self.balance = self.balance - amt def getbalance(self):

return self.balance

Using a class

a = Account(1000.00)a.deposit(550.23)a.deposit(100)a.withdraw(50)print a.getbalance()

O’Reilly OSCON 2000, Advanced Python Programming, Slide 16

July 17, 2000, [email protected]

Exceptions

The try statement

try:

f = open("foo") except IOError:

print "Couldn’t open ’foo’. Sorry."

The raise statement

def factorial(n):

if n < 0:

raise ValueError,"Expected non-negative number" if (n <= 1): return 1else: return n*factorial(n-1)

Uncaught exception

factorial(-1) Traceback (innermost last): File "", line 1, in ?File "", line 3, in factorial ValueError: Expected non-negative number>>>

O’Reilly OSCON 2000, Advanced Python Programming, Slide 17

July 17, 2000, [email protected]

Modules

Large programs can be broken into modules

numbers.pydef divide(a,b):

q = a/br = a - q*breturn q,r def gcd(x,y):

g = ywhile x > 0:

g = xx = y % xy = g return g

The import statement

import numbersx,y = numbers.divide(42,5)n = numbers.gcd(7291823, 5683) import creates a namespace and executes a file.

O’Reilly OSCON 2000, Advanced Python Programming, Slide 19

July 17, 2000, [email protected]

Python Library

Python is packaged with a large library of standard modules

String processingOperating system interfacesNetworkingThreadsGUIDatabaseLanguage servicesSecurity.

And there are many third party modules

XMLNumeric ProcessingPlotting/Graphicsetc.

All of these are accessed using ’import’

import string...a = string.split(x)

O’Reilly OSCON 2000, Advanced Python Programming, Slide 20

July 17, 2000, [email protected]