378
Python Programming Wikibooks.org

ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Pyth

onPr

ogra

mm

ing

Wik

iboo

ks.o

rg

Page 2: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

July

1,20

12

On

the

28th

ofA

pril

2012

the

cont

ents

ofth

eEn

glis

has

wel

las

Ger

man

Wik

iboo

ksan

dW

ikip

edia

proj

ects

wer

elic

ense

dun

-de

rCre

ativ

eC

omm

ons

Attr

ibut

ion-

Shar

eAlik

e3.

0U

npor

ted

licen

se.A

nU

RIt

oth

islic

ense

isgi

ven

inth

elis

toffi

gure

son

page

347.

Ifth

isdo

cum

enti

sa

deriv

edw

ork

from

the

cont

ents

ofon

eof

thes

epr

ojec

tsan

dth

eco

nten

twas

still

licen

sed

byth

epr

ojec

tun

der

this

licen

seat

the

time

ofde

rivat

ion

this

docu

men

thas

tobe

licen

sed

unde

rth

esa

me,

asi

mila

ror

aco

mpa

tible

licen

se,a

sst

ated

inse

ctio

n4b

ofth

elic

ense

.The

listo

fcon

tribu

tors

isin

clud

edin

chap

terC

ontri

buto

rson

page

329.

The

licen

sesG

PL,L

GPL

and

GFD

Lar

ein

clud

edin

chap

-te

rLic

ense

son

page

353,

sinc

eth

isbo

okan

d/or

parts

ofit

may

orm

ayno

tbe

licen

sed

unde

ron

eor

mor

eof

thes

elic

ense

s,an

dth

usre

quir

ein

clus

ion

ofth

ese

licen

ses.

The

licen

ses

ofth

efig

ures

are

give

nin

the

listo

ffigu

res

onpa

ge34

7.

Page 3: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Con

tent

s1

Ove

rvie

w.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.3

2G

ettin

gPy

thon

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.7

2.1

Pyth

on2

vsPy

thon

3.

..

..

..

..

..

..

..

..

..

..

..

..

72.

2In

stal

ling

Pyth

onin

Win

dow

s.

..

..

..

..

..

..

..

..

..

..

82.

3In

stal

ling

Pyth

onon

Mac

..

..

..

..

..

..

..

..

..

..

..

.10

2.4

Inst

allin

gPy

thon

onU

nix

envi

ronm

ents

..

..

..

..

..

..

..

..

112.

5K

eepi

ngU

pto

Dat

e.

..

..

..

..

..

..

..

..

..

..

..

..

.18

3In

tera

ctiv

em

ode

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.19

4C

reat

ing

Pyth

onpr

ogra

ms

..

..

..

..

..

..

..

..

..

..

..

..

.25

4.1

Hel

lo,W

orld

!.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

264.

2E

xerc

ises

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

314.

3N

otes

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.32

III

Page 4: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

5B

asic

synt

ax.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

336

Dat

aty

pes

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

437

Num

bers

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.49

8St

ring

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.53

8.1

Stri

ngm

anip

ulat

ion

..

..

..

..

..

..

..

..

..

..

..

..

..

539

Lis

ts.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

799.

1A

bout

lists

inPy

thon

..

..

..

..

..

..

..

..

..

..

..

..

.79

9.2

Lis

tmet

hods

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

959.

3op

erat

ors

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

9710

Dic

tiona

ries

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.99

10.1

Abo

utdi

ctio

nari

esin

Pyth

on.

..

..

..

..

..

..

..

..

..

..

9911

Sets

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.10

312

Ope

rato

rs.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.11

712

.1B

asic

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

117

12.2

Pow

ers

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.11

812

.3D

ivis

ion

and

Type

Con

vers

ion

..

..

..

..

..

..

..

..

..

..

119

12.4

Mod

ulo

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.121

12.5

Neg

atio

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..1

2112

.6A

ugm

ente

dA

ssig

nmen

t..

..

..

..

..

..

..

..

..

..

..

..

122

12.7

Boo

lean

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

123

Page 5: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

12.8

Ref

eren

ces

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.12

413

Flow

cont

rol

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.12

514

Func

tions

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

139

15Sc

opin

g.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.151

16E

xcep

tions

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

155

17In

puta

ndou

tput

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.16

517

.1In

put

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

165

17.2

Out

put

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.17

418

Mod

ules

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..1

8118

.1Im

port

ing

aM

odul

e.

..

..

..

..

..

..

..

..

..

..

..

..

..1

8118

.2C

reat

ing

aM

odul

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

184

18.3

Ext

erna

llin

ks.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

187

19C

lass

es.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

189

20M

etaC

lass

es.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

227

21R

egul

arE

xpre

ssio

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

235

21.1

Patte

rnob

ject

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

236

21.2

Mat

chin

gan

dse

arch

ing

..

..

..

..

..

..

..

..

..

..

..

..

.241

21.3

Rep

laci

ng.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

246

21.4

Oth

erfu

nctio

ns.

..

..

..

..

..

..

..

..

..

..

..

..

..

.24

721

.5E

xter

nall

inks

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.24

8

Page 6: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22G

UIP

rogr

amm

ing

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..2

5122

.1T

kint

er.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.251

22.2

PyG

TK

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

254

22.3

PyQ

t.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.25

522

.4w

xPyt

hon

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.25

622

.5D

abo

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

258

22.6

pyFl

tk.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

259

22.7

Oth

erTo

olki

ts.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

260

23G

ame

Prog

ram

min

gin

Pyth

on.

..

..

..

..

..

..

..

..

..

..

..

263

23.1

3DG

ame

Prog

ram

min

g.

..

..

..

..

..

..

..

..

..

..

..

.26

323

.22D

Gam

ePr

ogra

mm

ing

..

..

..

..

..

..

..

..

..

..

..

..

268

23.3

See

Als

o.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..2

7124

Sock

ets

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.27

324

.1H

TT

PC

lient

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

273

24.2

NT

P/So

cket

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

274

25Fi

les

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.27

525

.1Fi

leI/

O.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.27

525

.2Te

stin

gFi

les

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

279

25.3

Com

mon

File

Ope

ratio

ns.

..

..

..

..

..

..

..

..

..

..

..

.281

Page 7: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

26D

atab

ase

Prog

ram

min

g.

..

..

..

..

..

..

..

..

..

..

..

..

..

283

26.1

Gen

eric

Dat

abas

eC

onne

ctiv

ityus

ing

OD

BC

..

..

..

..

..

..

.28

326

.2Po

stgr

esco

nnec

tion

inPy

thon

..

..

..

..

..

..

..

..

..

..

286

26.3

MyS

QL

conn

ectio

nin

Pyth

on.

..

..

..

..

..

..

..

..

..

.28

726

.4SQ

LA

lche

my

inA

ctio

n.

..

..

..

..

..

..

..

..

..

..

..

.28

726

.5Se

eal

so.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.28

826

.6R

efer

ence

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

288

26.7

Ext

erna

llin

ks.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

288

27W

ebPa

geH

arve

stin

g.

..

..

..

..

..

..

..

..

..

..

..

..

..

..2

9128

Thr

eadi

ng.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.29

328

.1E

xam

ples

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.29

429

Ext

endi

ngw

ithC

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

297

29.1

Usi

ngth

ePy

thon

/CA

PI.

..

..

..

..

..

..

..

..

..

..

..

297

29.2

Usi

ngSW

IG.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.30

630

Ext

endi

ngw

ithC

++.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

309

30.1

AH

ello

Wor

ldE

xam

ple

..

..

..

..

..

..

..

..

..

..

..

..

310

30.2

An

exam

ple

with

CG

AL

..

..

..

..

..

..

..

..

..

..

..

.31

230

.3H

andl

ing

Pyth

onob

ject

san

der

rors

..

..

..

..

..

..

..

..

..

316

31W

SGIw

ebpr

ogra

mm

ing

..

..

..

..

..

..

..

..

..

..

..

..

..

319

Page 8: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

32W

SGIW

ebPr

ogra

mm

ing

..

..

..

..

..

..

..

..

..

..

..

..

..

.321

32.1

Ext

erna

lRes

ourc

es.

..

..

..

..

..

..

..

..

..

..

..

..

..3

2133

Ref

eren

ces

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

323

33.1

Lan

guag

ere

fere

nce

..

..

..

..

..

..

..

..

..

..

..

..

..

323

33.2

Ext

erna

llin

ks.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

324

34A

utho

rs.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

327

34.1

Aut

hors

ofPy

thon

text

book

..

..

..

..

..

..

..

..

..

..

..

327

35C

ontr

ibut

ors

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.32

9L

isto

fFig

ures

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

347

36L

icen

ses

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.35

336

.1G

NU

GE

NE

RA

LPU

BL

ICL

ICE

NSE

..

..

..

..

..

..

..

..

353

36.2

GN

UFr

eeD

ocum

enta

tion

Lic

ense

..

..

..

..

..

..

..

..

..

362

36.3

GN

UL

esse

rGen

eral

Publ

icL

icen

se.

..

..

..

..

..

..

..

..

369

Page 9: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 10: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1O

verv

iew

Pyth

on1

isa

high

-leve

l2 ,stru

ctur

ed3 ,o

pen-

sour

ce4

prog

ram

min

gla

ngua

geth

atca

nbe

used

fora

wid

eva

riet

yof

prog

ram

min

gta

sks.

Pyth

onw

ascr

eate

dby

Gud

ioV

anR

ossu

min

the

earl

y19

90s,

itsfo

llow

ing

has

grow

nst

eadi

lyan

din

tere

stis

incr

ease

dm

arke

dly

inth

ela

stfe

wye

ars

orso

.It

isna

med

afte

rM

onty

Pyth

on's

Flyi

ngC

ircu

sco

med

ypr

ogra

m.

1http://en.wikibooks.org/wiki/Python

2http://en.wikibooks.org/wiki/Computer%20programming%

2FHighlevel

3http://en.wikibooks.org/wiki/Computer%20programming%

2FStructured%20programming

4http://en.wikibooks.org/wiki/Open%20Source

3

Page 11: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Pyth

on5

isus

edex

tens

ivel

yfo

rsys

tem

adm

inis

tratio

n(m

any

vita

lcom

pone

nts

ofL

inux

6D

istr

ibut

ions

are

wri

tten

init)

,als

oits

agr

eatl

angu

age

tote

ach

prog

ram

min

gto

novi

ce.N

ASA

has

used

Pyth

onfo

rits

soft

war

esy

stem

san

dha

sad

opte

dit

asth

est

anda

rdsc

ript

ing

lang

uage

for

itsIn

tegr

ated

Plan

ning

Syst

em.P

ytho

nis

also

exte

nsiv

ely

used

byG

oogl

eto

impl

emen

tman

yco

m-

pone

nts

ofits

Web

Cra

wle

ran

dSe

arch

Eng

ine

&Y

ahoo

!fo

rm

anag

ing

itsdi

scus

sion

grou

ps.

Pyth

onw

ithin

itsel

fis

anin

terp

rete

dpr

ogra

mm

ing

lang

uage

that

isau

tom

ati-

cally

com

pile

din

toby

teco

debe

fore

exec

utio

n(t

heby

teco

deis

then

norm

ally

save

dto

disk

,jus

tas

auto

mat

ical

ly,s

oth

atco

mpi

latio

nne

edno

thap

pen

agai

nun

tilan

dun

less

the

sour

cege

tsch

ange

d).I

tis

also

ady

nam

ical

lyty

ped

lan-

guag

eth

atin

clud

es(b

utdo

esno

treq

uire

one

tous

e)ob

ject

orie

nted

feat

ures

and

cons

truc

ts.

5http://en.wikibooks.org/wiki/Python

6http://en.wikibooks.org/wiki/Linux

Page 12: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

mos

tunu

sual

aspe

ctof

Pyth

onis

that

whi

tesp

ace

issi

gnifi

cant

;ins

tead

ofbl

ock

delim

iters

(bra

ces→

"{}"

inth

eC

fam

ilyof

lang

uage

s),i

nden

tatio

nis

used

toin

dica

tew

here

bloc

ksbe

gin

and

end.

For

exam

ple,

the

follo

win

gPy

thon

code

can

bein

tera

ctiv

ely

type

dat

anin

terp

rete

rpro

mpt

,dis

play

the

fam

ous

"Hel

loW

orld

!"on

the

user

scre

en:

>>>

print"Hello

World!"

Hello

World!

Ano

ther

grea

tPyt

hon

feat

ure

isits

avai

labi

lity

fora

llPl

atfo

rms.

Pyth

onca

nru

non

Mic

roso

ftW

indo

ws,

Mac

into

sh&

allL

inux

dist

ribu

tions

with

ease

.Thi

sm

akes

the

prog

ram

sve

rypo

rtab

le,a

san

ypr

ogra

mw

ritte

nfo

rone

Plat

form

can

easi

lybe

used

atan

othe

r.

Pyth

onpr

ovid

esa

pow

erfu

lass

ortm

ento

fbui

lt-in

type

s(e

.g.,

lists

,dic

tiona

ries

and

stri

ngs)

,a

num

ber

ofbu

ilt-i

nfu

nctio

ns,

and

afe

wco

nstr

ucts

,m

ostly

stat

emen

ts.

For

exam

ple,

loop

cons

truc

tsth

atca

nite

rate

over

item

sin

aco

llect

ion

inst

ead

ofbe

ing

limite

dto

asi

mpl

era

nge

ofin

tege

rval

ues.

Pyth

on

Page 13: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

also

com

esw

itha

pow

erfu

lst

anda

rdlib

rary

7 ,w

hich

incl

udes

hund

reds

ofm

odul

esto

prov

ide

rout

ines

for

aw

ide

vari

ety

ofse

rvic

esin

clud

ing

regu

lar

expr

essi

ons8

and

TC

P/IP

sess

ions

.

Pyth

onis

used

and

supp

orte

dby

ala

rge

Pyth

onC

omm

unity

9th

atex

ists

onth

eIn

tern

et.T

hem

ailin

glis

tsan

dne

ws

grou

ps10

like

the

tuto

rlis

t11ac

tivel

ysu

ppor

tan

dhe

lpne

wpy

thon

prog

ram

mer

s.W

hile

they

disc

oura

gedo

ing

hom

ewor

kfo

ryou

,the

yar

equ

itehe

lpfu

land

are

popu

late

dby

the

auth

ors

ofm

any

ofth

ePy

thon

text

book

scu

rren

tlyav

aila

ble

onth

em

arke

t.

7http://en.wikibooks.org/wiki/Python%20Programming%

2FStandard%20Library

8C

hapt

er21

onpa

ge23

59

http://www.python.org/community/index.html

10http://www.python.org/community/lists.html

11http://mail.python.org/mailman/listinfo/tutor

Page 14: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2G

ettin

gPy

thon

Inor

der

topr

ogra

min

Pyth

onyo

une

edth

ePy

thon

inte

rpre

ter.

Ifit

isno

tal

read

yin

stal

led

orif

the

vers

ion

you

are

usin

gis

obso

lete

,you

will

need

toob

tain

and

inst

allP

ytho

nus

ing

the

met

hods

belo

w:

2.1

Pyth

on2

vsPy

thon

3

In20

08,

ane

wve

rsio

nof

Pyth

on(v

ersi

on3)

was

publ

ishe

dth

atw

asno

ten

tirel

yba

ckw

ard

com

patib

le.

Dev

elop

ers

wer

eas

ked

tosw

itch

toth

ene

wve

rsio

nas

soon

aspo

ssib

lebu

tman

yof

the

com

mon

exte

rnal

mod

ules

are

not

7

Page 15: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

yet(

asof

Aug

2010

)ava

ilabl

efo

rPyt

hon

3.T

here

isa

prog

ram

calle

d2t

o3to

conv

ertt

heso

urce

code

ofa

Pyth

on2

prog

ram

toth

eso

urce

code

ofa

Pyth

on3

prog

ram

.Con

side

rthi

sfa

ctbe

fore

you

star

twor

king

with

Pyth

on.

2.2

Inst

allin

gPy

thon

inW

indo

ws

Go

toth

ePy

thon

Hom

epag

e1or

the

Act

iveS

tate

web

site

2an

dge

tthe

prop

erve

rsio

nfo

ryo

urpl

atfo

rm.

Dow

nloa

dit,

read

the

inst

ruct

ions

and

geti

tin-

stal

led.

Inor

der

toru

nPy

thon

from

the

com

man

dlin

e,yo

uw

illne

edto

have

the

pyth

ondi

rect

ory

inyo

urPA

TH

.A

ltern

a-tiv

ely,

you

coul

dus

ean

Inte

grat

edD

evel

opm

ent

Env

iron

men

t(I

DE

)fo

rPy

thon

like

DrP

ytho

nhttp

://dr

pyth

on.s

ourc

efor

ge.n

et/3 ,

1http://www.python.org/download/

2http://activestate.com

3http://drpython.sourceforge.net/

Page 16: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

eric

http

://w

ww

.die

-off

enba

chs.

de/e

ric/

inde

x.ht

ml4 ,

PySc

ript

erht

tp://

mm

m-

expe

rts.

com

/Pro

duct

s.as

px?P

rodu

ctID

=45 ,

orPy

thon

'sow

nID

LE

6(w

hich

ship

sw

ithev

ery

vers

ion

ofPy

thon

sinc

e2.

3).

The

PAT

Hva

riab

leca

nbe

mod

ified

from

the

Win

dow

'sSy

stem

cont

rolp

anel

.T

head

vanc

edta

bw

illco

ntai

nth

ebu

tton

labe

lled

Env

iron

men

tVa

riab

les,

whe

reyo

uca

nap

pend

the

new

lycr

eate

dfo

lder

toth

ese

arch

path

.

Ifyo

upr

efer

havi

nga

tem

pora

ryen

viro

nmen

t,yo

uca

ncr

eate

ane

wco

mm

and

prom

ptsh

ort-

cutt

hata

utom

atic

ally

exec

utes

the

follo

win

gst

atem

ent:

4http://www.die-offenbachs.de/eric/index.html

5http://mmm-experts.com/Products.aspx?ProductID=4

6http://en.wikipedia.org/wiki/IDLE_%28Python%29

Page 17: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

PATH

%PATH%;c:\python26

Ifyo

udo

wnl

oade

da

diff

eren

tver

sion

(suc

has

Pyth

on3.

1),c

hang

eth

e"2

6"fo

rthe

vers

ion

ofPy

thon

you

have

(26

is2.

6.x,

the

curr

entv

ersi

onof

Pyth

on2.

)

2.2.

1C

ygw

in

By

defa

ult,

the

Cyg

win

inst

alle

rfor

Win

dow

sdo

esno

tinc

lude

Pyth

onin

the

dow

nloa

ds.H

owev

er,i

tcan

bese

lect

edfr

omth

elis

tofp

acka

ges.

2.3

Inst

allin

gPy

thon

onM

ac

Use

rson

App

leM

acO

SX

will

find

that

ital

read

ysh

ips

with

Pyth

on2.

3(O

SX

10.4

Tige

r)or

Pyth

on2.

6.1

(OS

XSn

owLe

opar

d),b

utif

you

wan

tthe

mor

e

Page 18: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

rece

ntve

rsio

nhe

adto

Pyth

onD

ownl

oad

Page

7fo

llow

the

inst

ruct

ion

onth

epa

gean

din

the

inst

alle

rs.A

sa

bonu

syo

uw

illal

soin

stal

lthe

Pyth

onID

E.

2.4

Inst

allin

gPy

thon

onU

nix

envi

ronm

ents

Pyth

onis

avai

labl

eas

apa

ckag

efo

rsom

eL

inux

dist

ribu

tions

.In

som

eca

ses,

the

dist

ribut

ion

CD

will

cont

ain

the

pyth

onpa

ckag

efo

rins

talla

tion,

whi

leot

her

dist

ribu

tions

requ

ire

dow

nloa

ding

the

sour

ceco

dean

dus

ing

the

com

pila

tion

scri

pts.

2.4.

1G

ento

oG

NU

/Lin

ux

Gen

too

isan

exam

ple

ofa

dist

ribu

tion

that

inst

alls

Pyth

onby

defa

ult-

the

pack

age

syst

emPo

rtag

ede

pend

son

Pyth

on.

7http://www.python.org/download/mac

Page 19: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2.4.

2U

bunt

uG

NU

/Lin

ux

Use

rsof

Ubu

ntu

will

notic

eth

atPy

thon

com

esin

stal

led

byde

faul

t,on

lyit

som

etim

esis

nott

hela

test

vers

ion.

Ifyo

uw

ould

like

toup

date

it,cl

ick

here

8 .

2.4.

3A

rch

GN

U/L

inux

Arc

hdo

esno

tins

tall

pyth

onby

defa

ult,

buti

sea

sily

avai

labl

efo

rins

talla

tion

thro

ugh

the

pack

age

man

ager

topa

cman

.A

sro

ot(o

rus

ing

sudo

ifyo

u've

inst

alle

dan

dco

nfigu

red

it),t

ype:

$pacman

-Sy

python

Thi

sw

illbe

upda

tepa

ckag

eda

taba

ses

and

inst

allp

ytho

n.O

ther

vers

ions

can

bebu

iltfr

omso

urce

from

the

Arc

hU

serR

epos

itory

.

8http://appnr.com/install/python

Page 20: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2.4.

4So

urce

code

inst

alla

tions

Som

epl

atfo

rms

dono

thav

ea

vers

ion

ofPy

thon

inst

alle

d,an

ddo

noth

ave

pre-

com

pile

dbi

nari

es.I

nth

ese

case

s,yo

uw

illne

edto

dow

nloa

dth

eso

urce

code

from

the

offic

ials

ite9 .O

nce

the

dow

nloa

dis

com

plet

e,yo

uw

illne

edto

unpa

ckth

eco

mpr

esse

dar

chiv

ein

toa

fold

er.

Tobu

ildPy

thon

,sim

ply

run

the

confi

gure

scri

pt(r

equi

res

the

Bas

hsh

ell)

and

com

pile

usin

gm

ake.

2.4.

5O

ther

Dis

trib

utio

ns

Pyth

on,w

hich

isal

sore

ferr

edto

asC

Pyth

on10

,is

wri

tten

inth

eC

Prog

ram

-m

ing11

lang

uage

.The

Cso

urce

code

isge

nera

llypo

rtabl

e,th

atm

eans

CPy

thon

9http://www.python.org/download/

10http://en.wikibooks.org/wiki/CPython

11http://en.wikibooks.org/wiki/C%20Programming

Page 21: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

can

run

onva

riou

spl

atfo

rms.

Mor

epr

ecis

ely,

CPy

thon

can

bem

ade

avai

labl

eon

allp

latfo

rms

that

prov

ide

aco

mpi

lert

otra

nsla

teth

eC

sour

ceco

deto

bina

ryco

defo

rtha

tpla

tfor

m.

Apa

rtfr

omC

Pyth

onth

ere

are

also

othe

rim

plem

enta

tions

that

run

onto

pof

avi

rtua

lmac

hine

.For

exam

ple,

onJa

va's

JRE

(Jav

aR

untim

eE

nvir

onm

ent)

orM

icro

soft

's.N

ET

CL

R(C

omm

onL

angu

age

Run

time)

.Bot

hca

nac

cess

and

use

the

libra

ries

avai

labl

eon

thei

rpl

atfo

rm.

Spec

ifica

lly,t

hey

mak

eus

eof

refle

ctio

n12th

atal

low

sco

mpl

ete

insp

ectio

nan

dus

eof

allc

lass

esan

dob

ject

sfo

rthe

irve

ryte

chno

logy

.

Pyt

hon

Impl

emen

tatio

ns(P

latfo

rms)

Env

iron

men

tD

escr

iptio

nG

etFr

omJy

thon

Java

Ver

sion

ofPy

thon

Jyth

on13

12http://en.wikipedia.org/wiki/Reflection_(computer_

programming)

13http://www.jython.org

Page 22: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Env

iron

men

tD

escr

iptio

nG

etFr

omIr

onPy

thon

C#

Ver

sion

ofPy

thon

Iron

Pyth

on14

2.4.

6In

tegr

ated

Dev

elop

men

tEnv

iron

men

ts(I

DE

)

CPy

thon

ship

sw

ithID

LE

15,a

nIn

tegr

ated

Dev

elop

men

tEnv

iron

men

tbui

ltw

ithth

etk

inte

rG

UI

tool

kit.

IDL

Eis

ais

mul

ti-w

indo

wte

xted

itor

and

debu

gger

,pro

vide

ssy

ntax

high

light

ing

and

anin

tera

ctiv

esh

ell

win

dow

,is

code

din

100%

pure

Pyth

onan

dth

eref

ore

cros

s-pl

atfo

rm(i

.e.

wor

kson

Win

dow

san

dU

nix)

.The

tabl

ebe

low

lists

som

eID

LE

alte

rnat

ives

.

Som

eIn

tegr

ated

Dev

elop

men

tEnv

iron

men

ts(I

DE

s)fo

rP

ytho

n

Env

iron

men

tD

escr

iptio

nG

etFr

om

14http://www.ironpython.net

15http://en.wikibooks.org/wiki/IDLE

Page 23: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Env

iron

men

tD

escr

iptio

nG

etFr

omE

clip

seO

pen

Sour

ceID

EE

clip

se16

KD

evel

opC

ross

Lan

guag

eID

Efo

rKD

EK

Dev

elop

17

Act

iveP

ytho

nH

ighl

yFl

exib

le,

Pyth

onw

inID

EA

ctiv

ePyt

hon18

Anj

uta

IDE

Lin

ux/U

nix

Anj

uta19

Pyth

onw

inW

indo

ws

Ori

ente

dE

nvir

onm

ent

Pyth

onw

in20

Vis

ualW

xFr

eeG

UIB

uild

erV

isua

lWx21

Kom

odo

AC

omm

erci

alID

EK

omod

o22

16http://www.eclipse.org

17http://www.kdevelop.org

18http://www.activestate.com/

19http://anjuta.sf.net/

20http://www.python.org/windows/

21http://visualwx.altervista.org

22http://www.activestate.com/komodo-ide/

Page 24: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Env

iron

men

tD

escr

iptio

nG

etFr

omB

lack

Add

erC

omm

erci

alID

E&

GU

IBui

lder

Bla

ckA

dder

23

Cod

eC

rusa

der

Com

mer

cial

IDE

Cod

eC

rusa

der24

Cod

eFo

rge

Com

mer

cial

IDE

Cod

eFo

rge25

PyC

harm

Com

mer

cial

IDE

PyC

harm

26

23http://www.thekompany.com/

24http://www.newplanetsoftware.com/

25http://www.codeforge.com/

26http://www.jetbrains.com/pycharm/

Page 25: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2.5

Kee

ping

Up

toD

ate

Pyth

onha

sa

very

activ

eco

mm

unity

and

lang

uage

itsel

fevo

lves

cont

inuo

usly

.D

ofr

eque

ntly

visi

tPy

thon

.Org

27fo

rrec

entr

elea

ses

and

rele

vant

tool

s.T

hew

ebsi

teis

anin

valu

able

asse

t.

Ifyo

uw

ant

toke

epup

with

new

lyre

leas

edth

ird

part

y-m

odul

esor

soft

-w

are

for

Pyth

on,

have

alo

okat

Pyth

onem

ail

list

pyth

on-a

nnou

nce-

list.

Gen

eral

disc

ussi

onca

nbe

foun

dat

pyth

on-li

st,

both

ofth

ese

lists

can

befo

und

atPy

thon

Mai

l28.

Use

net

user

sca

nea

sily

user

the

new

sgro

ups

com

p.la

ng.p

ytho

n.an

noun

ce&

com

p.la

ng.p

ytho

n.

27http://www.python.org

28http://mail.python.org

Page 26: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

3In

tera

ctiv

em

ode

Pyth

onha

stw

oba

sic

mod

es:

norm

alan

din

tera

ctiv

e.T

heno

rmal

mod

eis

the

mod

ew

here

the

scri

pted

and

finis

hed.py

files

are

run

inth

ePy

thon

inte

rpre

ter.

Inte

ract

ive

mod

eis

aco

mm

and

line

shel

lwhi

chgi

ves

imm

edia

tefe

edba

ckfo

reac

hst

atem

ent,

whi

leru

nnin

gpr

evio

usly

fed

stat

emen

tsin

activ

em

emor

y.A

sne

wlin

esar

efe

din

toth

ein

terp

rete

r,th

efe

dpr

ogra

mis

eval

uate

dbo

thin

part

and

inw

hole

.

Tost

arti

nter

activ

em

ode,

sim

ply

type

"pyt

hon"

with

outa

nyar

gum

ents

.Thi

sis

ago

odw

ayto

play

arou

ndan

dtry

varia

tions

onsy

ntax

.Pyt

hon

shou

ldpr

int

som

ethi

nglik

eth

is:

19

Page 27: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

$python

Python

3.0b3

(r30b3:66303,

Sep

82008,

14:01:02)

[MSC

v.1500

32

bit

(Intel)]

on

win32

Type

"help",

"copyright",

"credits"

or

"license"

for

more

information.

>>>

(If

Pyth

ondo

esn'

tru

n,m

ake

sure

your

path

isse

tco

rrec

tly.

See

Get

ting

Pyth

on1 .)

The

>>>

isPy

thon

'sw

ayof

telli

ngyo

uth

atyo

uar

ein

inte

ract

ive

mod

e.In

inte

ract

ive

mod

ew

haty

outy

peis

imm

edia

tely

run.

Try

typi

ng1+1

in.P

ytho

nw

illre

spon

dw

ith2

.In

tera

ctiv

em

ode

allo

ws

you

tote

stou

tand

see

wha

tPy

thon

will

do.I

fyou

ever

feel

the

need

topl

ayw

ithne

wPy

thon

stat

emen

ts,

goin

toin

tera

ctiv

em

ode

and

try

them

out.

Asa

mpl

ein

tera

ctiv

ese

ssio

n:

1C

hapt

er2

onpa

ge7

Page 28: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

55 >>>

print

(5*7)

35

>>>

"hello"*4

'hellohellohellohello'

>>>

"hello".__class__

<type

'str'>

How

ever

,you

need

tobe

care

fuli

nth

ein

tera

ctiv

een

viro

nmen

tto

avoi

dco

nfu-

sion

.For

exam

ple,

the

follo

win

gis

ava

lidPy

thon

scri

pt:

if

1:

print("True")

print("Done")

Ifyo

utr

yto

ente

rthi

sas

wri

tten

inth

ein

tera

ctiv

een

viro

nmen

t,yo

um

ight

besu

rpri

sed

byth

ere

sult:

Page 29: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

if

1:

...

print("True")

...

print("Done")

File

"<stdin>",

line

3print("Done")

ˆSyntaxError:

invalid

syntax

Wha

tthe

inte

rpre

teri

ssa

ying

isth

atth

ein

dent

atio

nof

the

seco

ndpr

intw

asun

expe

cted

.Y

oush

ould

have

ente

red

abl

ank

line

toen

dth

efir

st(i

.e.,

"if"

)st

atem

ent,

befo

reyo

ust

arte

dw

ritin

gth

ene

xtpr

ints

tate

men

t.Fo

rex

ampl

e,yo

ush

ould

have

ente

red

the

stat

emen

tsas

thou

ghth

eyw

ere

wri

tten:

if

1:

print("True")

print("Done")

Whi

chw

ould

have

resu

lted

inth

efo

llow

ing:

Page 30: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

if

1:

...

print("True")

...

True

>>>

print("Done")

Done

>>>

3.0.

1In

tera

ctiv

em

ode

Inst

ead

ofPy

thon

exiti

ngw

hen

the

prog

ram

isfin

ishe

d,yo

uca

nus

eth

e-i

flag

tost

arta

nin

tera

ctiv

ese

ssio

n.T

his

can

beve

ryus

eful

ford

ebug

ging

and

prot

otyp

ing.

python

-i

hello.py

Page 31: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 32: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

4C

reat

ing

Pyth

onpr

ogra

ms

Wel

com

eto

Pyth

on!

This

tuto

rialw

illsh

owyo

uho

wto

star

twrit

ing

prog

ram

s.

Pyth

onpr

ogra

msa

reno

thin

gm

ore

than

text

files

,and

they

may

beed

ited

with

ast

anda

rdte

xted

itor1

prog

ram

.2W

hatt

exte

dito

ryou

use

will

prob

ably

depe

ndon

your

oper

atin

gsy

stem

:an

yte

xted

itor

can

crea

tePy

thon

prog

ram

s.It

isea

sier

tous

ea

text

edito

rtha

tinc

lude

sPy

thon

synt

axhi

ghlig

htin

g3 ,how

ever

.

1http://en.wikipedia.org/wiki/Text%20editor

2So

met

imes

,Pyt

hon

prog

ram

sar

edi

stri

bute

din

com

pile

dfo

rm.W

ew

on't

have

tow

orry

abou

ttha

tfor

quite

aw

hile

.3

http://en.wikipedia.org/wiki/Syntax%20highlighting

25

Page 33: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

4.1

Hel

lo,W

orld

!

The

first

prog

ram

that

ever

ypr

ogra

mm

erw

rite

sis

calle

dth

e"H

ello

,Wor

ld!"

prog

ram

.Thi

spr

ogra

msi

mpl

you

tput

sth

eph

rase

"Hel

lo,W

orld

!"an

dth

enen

ds.L

et's

wri

te"H

ello

,Wor

ld!"

inPy

thon

!

Ope

nup

your

text

edito

rand

crea

tea

new

file

calle

dhello.py

cont

aini

ngju

stth

islin

e(y

ouca

nco

py-p

aste

ifyo

uw

ant)

:

print("Hello,

world!")

or def

hello(message):

message

="Hello,

world!"

print(message)

returnmessage

print(hello("message"))

Page 34: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

spr

ogra

mus

esth

eprint

func

tion,

whi

chsi

mpl

you

tput

sits

para

met

ers

toth

ete

rmin

al.print

ends

with

anewline

char

acte

r,w

hich

sim

ply

mov

esth

ecu

rsor

toth

ene

xtlin

e.

Now

that

you'

vew

ritte

nyo

urfir

stpr

ogra

m,l

et's

run

itin

Pyth

on!

This

proc

ess

diff

ers

slig

htly

depe

ndin

gon

your

oper

atin

gsy

stem

.

Not

e:In

Pyth

on2.

6,pr

inti

sa

stat

emen

trat

hert

han

afu

nctio

n.A

ssu

ch,i

tprin

ted

ever

ythi

ngun

tilth

een

dof

the

line,

did

notu

tiliz

epa

rent

hesi

san

dre

quire

dus

ing

ast

anda

lone

com

ma

afte

rthe

final

prin

ted

item

toid

entif

yth

atth

ecu

rren

tlin

ew

asno

tyet

com

plet

e.

4.1.

1W

indo

ws

•C

reat

ea

fold

eron

your

com

pute

rto

use

fory

ourP

ytho

npr

ogra

ms,

such

asC:\pythonpractice

,and

save

yourhello.py

prog

ram

inth

atfo

lder

.

Page 35: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•In

the

Star

tm

enu,

sele

ct"R

un...

",an

dty

peincmd

.T

his

will

caus

eth

eW

indo

ws

term

inal

toop

en.

•Ty

pecd\pythonpractice

toch

ange

dire

ctor

yto

your

pythonpractice

fold

er,a

ndhi

tEnt

er.

•Ty

pepythonhello.py

toru

nyo

urpr

ogra

m!

Ifit

didn

'tw

ork,

mak

esu

reyo

urPA

TH

cont

ains

the

pyth

ondi

rect

ory.

See

Get

ting

Pyth

on4 .

4.1.

2M

ac

•C

reat

ea

fold

eron

your

com

pute

rto

use

fory

ourP

ytho

npr

ogra

ms.

Ago

odsu

gges

tion

wou

ldbe

tona

me

itpythonpractice

and

plac

eit

inyo

urH

ome

fold

er(t

heon

eth

atco

ntai

nsfo

lder

sfo

rDoc

umen

ts,M

ovie

s,M

usic

,Pi

ctur

es,e

tc).

Save

yourhello.py

prog

ram

into

this

fold

er.

4C

hapt

er2

onpa

ge7

Page 36: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•O

pen

the

App

licat

ions

fold

er,

goin

toth

eU

tiliti

esfo

lder

,an

dop

enth

eTe

rmin

alpr

ogra

m.

•Ty

pecdpythonpractice

toch

ange

dire

ctor

yto

your

pythonpractice

fold

er,a

ndhi

tEnt

er.

•Ty

pepythonhello.py

toru

nyo

urpr

ogra

m!

4.1.

3L

inux

•C

reat

ea

fold

eron

your

com

pute

rto

use

fory

ourP

ytho

npr

ogra

ms,

such

as˜/pythonpractice

,and

save

yourhello.py

prog

ram

inth

atfo

lder

.•

Ope

nup

the

term

inal

prog

ram

.In

KD

E,o

pen

the

mai

nm

enu

and

sele

ct"R

unC

omm

and.

.."to

open

Kon

sole

.In

GN

OM

E,op

enth

em

ain

men

u,op

enth

eA

pplic

atio

nsfo

lder

,ope

nth

eA

cces

sori

esfo

lder

,and

sele

ctTe

rmin

al.

•Ty

pecd˜/pythonpractice

toch

ange

dire

ctor

yto

your

pythonpractice

fold

er,a

ndhi

tEnt

er.

•Ty

pepythonhello.py

toru

nyo

urpr

ogra

m!

Page 37: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Not

e:If

you

have

both

pyth

onve

rsio

n2.

6.1

and

vers

ion

3.0

inst

alle

d(V

ery

poss

ible

ifyo

uar

eus

ing

Ubu

ntu,

and

ran

sudo

apt-

getp

ytho

n3to

have

pyth

on3

inst

alle

d),y

oush

ould

runpython3hello.py

An

Alte

rnat

ive

The

reis

afil

eca

lledidle.py

inyo

urPy

thon

file.

Itis

inth

eid

lelib

fold

er,

loca

ted

inth

eLi

bfo

lder

.Thi

sis

aPy

thon

prog

ram

mer

writ

ten

inPy

thon

.You

mig

htfin

dit

abi

teas

iert

ous

eth

ancm

d.

4.1.

4R

esul

t

The

prog

ram

shou

ldpr

int:

Page 38: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Hello,

world!

Con

grat

ulat

ions

!Y

ou're

wel

lon

your

way

tobe

com

ing

aPy

thon

prog

ram

mer

.

4.2

Exe

rcis

es

1.M

odif

yth

ehello.py

prog

ram

tosa

yhe

lloto

ahi

stor

ical

polit

ical

lead

er(o

rto

Ada

Lov

elac

e5 ).2.

Cha

nge

the

prog

ram

soth

ataf

tert

hegr

eetin

g,it

asks

,"H

owdi

dyo

uge

the

re?"

.3.

Re-

wri

teth

eor

igin

alpr

ogra

mto

use

twoprint

stat

emen

ts:

one

for

"Hel

lo"

and

one

for"

wor

ld".

The

prog

ram

shou

ldst

illon

lypr

into

uton

one

line.

5http://en.wikipedia.org/wiki/Ada%20Lovelace

Page 39: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Solu

tions

6

4.3

Not

es

6http://en.wikibooks.org/wiki/Python%20Programming%

2FCreating%20Python%20programs%2FSolutions

Page 40: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

5B

asic

synt

ax

The

rear

efiv

efu

ndam

enta

lcon

cept

sin

Pyth

on1 .

5.0.

1C

ase

Sens

itivi

ty

All

vari

able

sar

eca

se-s

ensi

tive.

Pyth

ontr

eats

'num

ber'

and

'Num

ber'

asse

pa-

rate

,unr

elat

eden

titie

s.

1http://en.wikibooks.org/wiki/Python%20Programming

33

Page 41: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

5.0.

2Sp

aces

and

tabs

don'

tmix

Bec

ause

whi

tesp

ace

issi

gnifi

cant

,rem

embe

rtha

tspa

ces

and

tabs

don'

tmix

,so

use

only

one

orth

eot

herw

hen

inde

ntin

gyo

urpr

ogra

ms.

Aco

mm

oner

rori

sto

mix

them

.Whi

leth

eym

aylo

okth

esa

me

ined

itor,

the

inte

rpre

terw

illre

adth

emdi

ffer

ently

and

itw

illre

sult

inei

ther

aner

ror

orun

expe

cted

beha

vior

.M

ostd

ecen

ttex

tedi

tors

can

beco

nfigu

red

tole

ttab

key

emit

spac

esin

stea

d.

Pyth

on's

Styl

eG

uide

line

desc

ribe

dth

atth

epr

efer

red

way

isus

ing

4sp

aces

.

Tips

:Ify

ouin

voke

dpy

thon

from

the

com

man

d-lin

e,yo

uca

ngi

ve-t

or-t

tar

gum

entt

opy

thon

tom

ake

pyth

onis

sue

aw

arni

ngor

erro

ron

inco

nsis

tent

tab

usag

e.

pythonprogrammer@wikibook:

$python

-tt

myscript.py

Page 42: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illis

sue

aner

rori

fyou

have

mix

edsp

aces

and

tabs

.

5.0.

3O

bjec

ts

InPy

thon

,lik

eal

lobj

ecto

rien

ted

lang

uage

s,th

ere

are

aggr

egat

ions

ofco

dean

dda

taca

lled

Obj

ects

,whi

chty

pica

llyre

pres

entt

hepi

eces

ina

conc

eptu

alm

odel

ofa

syst

em.

Obj

ects

inPy

thon

are

crea

ted

(i.e.

,ins

tant

iate

d)fr

omte

mpl

ates

calle

dC

lass

es2

(whi

char

eco

vere

dla

ter,

asm

uch

ofth

ela

ngua

geca

nbe

used

with

outu

nder

-st

andi

ngcl

asse

s).T

hey

have

"attr

ibut

es",

whi

chre

pres

entt

heva

riou

spi

eces

ofco

dean

dda

taw

hich

com

pris

eth

eob

ject

.To

acce

ssat

trib

utes

,one

wri

tes

the

nam

eof

the

obje

ctfo

llow

edby

ape

riod

(hen

cefo

rthca

lled

ado

t),fo

llow

edby

the

nam

eof

the

attr

ibut

e.

2C

hapt

er19

onpa

ge18

9

Page 43: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

An

exam

ple

isth

e'u

pper

'attr

ibut

eof

stri

ngs,

whi

chre

fers

toth

eco

deth

atre

turn

sa

copy

ofth

est

ring

inw

hich

allt

hele

tters

are

uppe

rcas

e.To

gett

oth

is,

itis

nece

ssar

yto

have

aw

ayto

refe

rto

the

obje

ct(i

nth

efo

llow

ing

exam

ple,

the

way

isth

elit

eral

stri

ngth

atco

nstr

ucts

the

obje

ct).

'bob'.upper

Cod

eat

tribu

tes

are

calle

d"m

etho

ds".

Soin

this

exam

ple,

uppe

ris

am

etho

dof

'bob

'(as

itis

ofal

lstri

ngs)

.To

exec

ute

the

code

ina

met

hod,

use

am

atch

edpa

irof

pare

nthe

ses

surr

ound

ing

aco

mm

ase

para

ted

listo

fwha

teve

rarg

umen

tsth

em

etho

dac

cept

s(u

pper

does

n'ta

ccep

tany

argu

men

ts).

Soto

find

anup

perc

ase

vers

ion

ofth

est

ring

'bob

',on

eco

uld

use

the

follo

win

g:

'bob'.upper()

Page 44: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

5.0.

4Sc

ope

Ina

larg

esy

stem

,iti

sim

porta

ntth

aton

epi

ece

ofco

dedo

esno

taff

ecta

noth

erin

diffi

cult

topr

edic

tway

s.O

neof

the

sim

ples

tway

sto

furt

her

this

goal

isto

prev

ento

nepr

ogra

mm

er's

choi

ceof

nam

esfr

ompr

even

ting

anot

herf

rom

choo

sing

that

nam

e.B

ecau

seof

this

,the

conc

epto

fsc

ope

was

inve

nted

.A

scop

eis

a"r

egio

n"of

code

inw

hich

ana

me

can

beus

edan

dou

tsid

eof

whi

chth

ena

me

cann

otbe

easi

lyac

cess

ed.T

here

are

two

way

sof

delim

iting

regi

ons

inPy

thon

:with

func

tions

orw

ithm

odul

es.T

hey

each

have

diff

eren

tway

sof

acce

ssin

gth

eus

eful

data

that

was

prod

uced

with

inth

esc

ope

from

outs

ide

the

scop

e.W

ithfu

nctio

ns,t

hatw

ayis

tore

turn

the

data

.The

way

toac

cess

nam

esfr

omot

herm

odul

esle

adus

toan

othe

rcon

cept

.

5.0.

5N

ames

pace

s

Itw

ould

bepo

ssib

leto

teac

hPy

thon

with

out

the

conc

ept

ofna

mes

pace

sbe

caus

eth

eyar

eso

sim

ilart

oat

tribu

tes,

whi

chw

eha

veal

read

ym

entio

ned,

but

Page 45: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

the

conc

epto

fnam

espa

ces

ison

eth

attr

ansc

ends

any

part

icul

arpr

ogra

mm

ing

lang

uage

,an

dso

itis

impo

rtan

tto

teac

h.To

begi

nw

ith,

ther

eis

abu

ilt-

infu

nctio

ndir()

that

can

beus

edto

help

one

unde

rsta

ndth

eco

ncep

tof

nam

espa

ces.

Whe

nyo

ufir

stst

artt

hePy

thon

inte

rpre

ter

(i.e

.,in

inte

ract

ive

mod

e),y

ouca

nlis

tthe

obje

cts

inth

ecu

rren

t(or

defa

ult)

nam

espa

ceus

ing

this

func

tion.

Python

2.3.4

(#53,

Oct

18

2004,

20:35:07)

[MSC

v.1200

32

bit

(Intel)]

on

win32

Type

"help",

"copyright",

"credits"

or

"license"

formore

information.

>>>

dir()

['__builtins__',

'__doc__',

'__name__']

Thi

sfu

nctio

nca

nal

sobe

used

tosh

owth

ena

mes

avai

labl

ew

ithin

am

odul

ena

mes

pace

.To

dem

onst

rate

this

,firs

tw

eca

nus

eth

etype()

func

tion

tosh

oww

hat_

_bui

ltins

__is

:

>>>

type(__builtins__)

<type

'module'>

Page 46: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Sinc

eit

isa

mod

ule,

we

can

listt

hena

mes

with

inth

e__

built

ins_

_nam

espa

ce,

agai

nus

ing

thedir()

func

tion

(not

eth

eco

mpl

ete

listo

fna

mes

has

been

abbr

evia

ted)

:

>>>

dir(__builtins__)

['ArithmeticError',

...

'copyright',

'credits',

...

'help',

...

'license',

...

'zip']

>>>

Nam

espa

ces

are

asi

mpl

eco

ncep

t.A

nam

espa

ceis

apl

ace

inw

hich

ana

me

resi

des.

Eac

hna

me

with

ina

nam

espa

ceis

dist

inct

from

nam

esou

tsid

eof

the

nam

espa

ce.

Thi

sla

yeri

ngof

nam

espa

ces

isca

lled

scop

e.A

nam

eis

plac

edw

ithin

ana

mes

pace

whe

nth

atna

me

isgi

ven

ava

lue.

Fore

xam

ple:

>>>

dir()

['__builtins__',

'__doc__',

'__name__']

>>>

name

="Bob"

>>>

import

math

>>>

dir()

['__builtins__',

'__doc__',

'__name__',

'math',

'name']

Page 47: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Not

eth

atIw

asab

leto

add

the

"nam

e"va

riabl

eto

the

nam

espa

ceus

ing

asi

mpl

eas

sign

men

tsta

tem

ent.

The

impo

rtst

atem

entw

asus

edto

add

the

"mat

h"na

me

toth

ecu

rren

tnam

espa

ce.T

ose

ew

hatm

ath

is,w

eca

nsi

mpl

y:

>>>

math

<module

'math'

(built-in)>

Sinc

eit

isa

mod

ule,

ital

soha

sa

nam

espa

ce.T

odi

spla

yth

ena

mes

with

inth

isna

mes

pace

,we:

>>>

dir(math)

['__doc__',

'__name__',

'acos',

'asin',

'atan',

'atan2',

'ceil',

'cos',

'cosh',

'degrees',

'e',

'exp',

'fabs',

'floor',

'fmod',

'frexp',

'hypot',

'ldexp',

'log',

'log10',

'modf',

'pi',

'pow',

'radians',

'sin',

'sinh',

'sqrt',

'tan',

'tanh']

>>>

Ifyo

ulo

okcl

osel

y,yo

uw

illno

tice

that

both

the

defa

ultn

ames

pace

,and

the

mat

hm

odul

ena

mes

pace

have

a'_

_nam

e__'

obje

ct.

The

fact

that

each

laye

r

Page 48: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

can

cont

ain

anob

ject

with

the

sam

ena

me

isw

hats

cope

isal

labo

ut.T

oac

cess

obje

cts

insi

dea

nam

espa

ce,s

impl

yus

eth

ena

me

ofth

em

odul

e,fo

llow

edby

ado

t,fo

llow

edby

the

nam

eof

the

obje

ct.T

his

allo

wus

todi

ffer

entia

tebe

twee

nth

e__name__

obje

ctw

ithin

the

curr

entn

ames

pace

,and

that

ofth

eob

ject

with

the

sam

ena

me

with

inth

emath

mod

ule.

Fore

xam

ple:

>>>

print__name__

__main__

>>>

printmath.__name__

math

>>>

printmath.__doc__

This

module

is

always

available.

It

provides

access

to

the

mathematical

functions

defined

by

the

Cstandard.

>>>

math.pi

3.1415926535897931

Page 49: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 50: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

6D

ata

type

s

Dat

aty

pes

dete

rmin

ew

heth

eran

obje

ctca

ndo

som

ethi

ng,o

rwhe

ther

itju

stw

ould

notm

ake

sens

e.O

ther

prog

ram

min

gla

ngua

ges

ofte

nde

term

ine

whe

ther

anop

erat

ion

mak

esse

nse

fora

nob

ject

bym

akin

gsu

reth

eob

ject

can

neve

rbe

stor

edso

mew

here

whe

reth

eop

erat

ion

will

bepe

rfor

med

onth

eob

ject

(thi

sty

pesy

stem

1is

calle

dst

atic

typi

ng).

Pyth

ondo

esno

tdo

that

.Ins

tead

itst

ores

the

type

ofan

obje

ctw

ithth

eob

ject

,and

chec

ksw

hen

the

oper

atio

nis

perf

orm

edw

heth

erth

atop

erat

ion

mak

esse

nse

for

that

obje

ct(t

his

isca

lled

dyna

mic

typi

ng).

1http://en.wikipedia.org/wiki/Type_system%23Type%20checking

43

Page 51: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Pyth

on's

basi

cda

taty

pes

are:

•In

tege

rs,e

quiv

alen

tto

Clo

ngs

•Fl

oatin

g-Po

intn

umbe

rs,e

quiv

alen

tto

Cdo

uble

s•

Lon

gin

tege

rsof

non-

limite

dle

ngth

•C

ompl

exN

umbe

rs.

•St

ring

s•

Som

eot

hers

,suc

has

type

and

func

tion

Pyth

on's

com

posi

teda

taty

pes

are:

•lis

ts•

tupl

es•

dict

iona

ries

,als

oca

lled

dict

s,ha

shm

aps,

oras

soci

ativ

ear

rays

Lite

rali

nteg

ers

can

been

tere

das

inC

:

•de

cim

alnu

mbe

rsca

nbe

ente

red

dire

ctly

•oc

tal

num

bers

can

been

tere

dby

prep

endi

nga

0(0

732

isoc

tal

732,

for

exam

ple)

Page 52: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•he

xade

cim

alnu

mbe

rsca

nbe

ente

red

bypr

epen

ding

a0x

(0xf

fis

hex

FF,o

r25

5in

deci

mal

)

Floa

ting

poin

tnum

bers

can

been

tere

ddi

rect

ly.

Lon

gin

tege

rsar

een

tere

dei

ther

dire

ctly

(123

4567

8910

1112

1314

1516

1718

1920

isa

long

inte

ger)

orby

appe

ndin

gan

L(0

Lis

alo

ngin

tege

r).C

ompu

tatio

nsin

volv

ing

shor

tint

eger

sth

atov

erflo

war

eau

tom

atic

ally

turn

edin

tolo

ngin

tege

rs.

Com

plex

num

bers

are

ente

red

byad

ding

are

alnu

mbe

rand

anim

agin

ary

one,

whi

chis

ente

red

byap

pend

ing

aj(

i.e.1

0+5j

isa

com

plex

num

ber.

Sois

10j)

.N

ote

that

jby

itsel

fdoe

sno

tcon

stitu

tea

num

ber.

Ifth

isis

desi

red,

use

1j.

Stri

ngs

can

beei

ther

sing

leor

trip

lequ

oted

stri

ngs.

The

diff

eren

ceis

inth

est

artin

gan

den

ding

delim

iters

,and

inth

atsi

ngle

quot

edst

ring

sca

nnot

span

mor

eth

anon

elin

e.Si

ngle

quot

edst

ring

sar

een

tere

dby

ente

ring

eith

era

sing

lequ

ote

(')or

ado

uble

quot

e("

)fol

low

edby

itsm

atch

.So

ther

efor

e

Page 53: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

'foo'

works,

and

"moo"

works

as

well,

but

'bar"

does

not

work,

and

"baz'

does

not

work

either.

"quux''

is

right

out.

Trip

lequ

oted

strin

gsar

elik

esi

ngle

quot

edst

rings

,but

can

span

mor

eth

anon

elin

e.T

heir

star

ting

and

endi

ngde

limite

rsm

usta

lso

mat

ch.T

hey

are

ente

red

with

thre

eco

nsec

utiv

esi

ngle

ordo

uble

quot

es,s

o

'''foo'''

works,

and

"""moo"""

works

as

well,

but

'"'bar'"'

does

not

work,

and

"""baz'''

does

not

work

either.

'"'quux"'"

is

right

out.

Tupl

esar

een

tere

din

pare

nthe

sis,

with

com

mas

betw

een

the

entr

ies:

Page 54: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

(10,

'Mary

had

alittle

lamb')

Als

o,th

epa

rent

hesi

sca

nbe

left

outw

hen

it's

nota

mbi

guou

sto

doso

:

10,

'whose

fleece

was

as

white

as

snow'

Not

eth

aton

e-el

emen

ttup

les

can

been

tere

dby

surr

ound

ing

the

entr

yw

ithpa

rent

hese

san

dad

ding

aco

mm

alik

eso

:

('this

is

astupid

tuple',)

Lis

tsar

esi

mila

r,bu

twith

brac

kets

:

['abc',

1,2,3]

Dic

tsar

ecr

eate

dby

surr

ound

ing

with

curl

ybr

aces

alis

tof

key,

valu

epa

irs

sepa

rate

dfr

omea

chot

herb

ya

colo

nan

dfr

omth

eot

here

ntri

esw

ithco

mm

as:

Page 55: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

{'hello':

'world',

'weight':

'African

or

European?'

}

Any

ofth

ese

com

posi

tety

pes

can

cont

ain

any

othe

r,to

any

dept

h:

((((((((('bob',),['Mary',

'had',

'a',

'little',

'lamb']),

{'hello'

:'world'

}),),),),),),)

Page 56: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

7N

umbe

rs

Pyth

onsu

ppor

ts4

type

sofN

umbe

rs,t

hein

t,th

elo

ng,t

heflo

atan

dth

eco

mpl

ex.

You

don’

thav

eto

spec

ify

wha

ttyp

eof

vari

able

you

wan

t;Py

thon

does

that

auto

mat

ical

ly.

•In

t:T

his

isth

eba

sic

inte

gert

ype

inpy

thon

,iti

seq

uiva

lent

toth

eha

rdw

are

'clo

ng'f

orth

epl

atfo

rmyo

uar

eus

ing.

•Lo

ng:

Thi

sis

ain

tege

rnu

mbe

rth

at's

leng

this

non-

limite

d.In

pyth

on2.

2an

dla

ter,

Ints

are

auto

mat

ical

lytu

rned

into

long

ints

whe

nth

eyov

erflo

w.

•F

loat

:T

his

isa

bina

ryflo

atin

gpo

intn

umbe

r.L

ongs

and

Ints

are

auto

mat

i-ca

llyco

nver

ted

toflo

ats

whe

na

float

isus

edin

anex

pres

sion

,and

with

the

true

-div

isio

n//

oper

ator

.

49

Page 57: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•C

ompl

ex:

Thi

sis

aco

mpl

exnu

mbe

rco

nsis

ting

oftw

oflo

ats.

Com

plex

liter

als

are

wri

tten

asa

+bj

whe

rea

and

bar

eflo

atin

g-po

int

num

bers

deno

ting

the

real

and

imag

inar

ypa

rts

resp

ectiv

ely.

Inge

nera

l,th

enu

mbe

rtyp

esar

eau

tom

atic

ally

'up

cast

'in

this

orde

r:

Int→

Lon

g→

Floa

t→C

ompl

ex.T

hefa

rthe

rto

the

righ

tyou

go,t

hehi

gher

the

prec

eden

ce.

>>>

x=

5>>>

type(x)

<type

'int'>

>>>

x=

187687654564658970978909869576453

>>>

type(x)

<type

'long'>

>>>

x=

1.34763

>>>

type(x)

<type

'float'>

>>>

x=

5+

2j

>>>

type(x)

<type

'complex'>

Page 58: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

How

ever

,som

eex

pres

sion

sm

aybe

conf

usin

gsi

nce

inth

ecu

rren

tver

sion

ofpy

thon

,usi

ngth

e/o

pera

toro

ntw

oin

tege

rsw

illre

turn

anot

heri

nteg

er,u

sing

floor

divi

sion

.Fo

rex

ampl

e,5/2

will

give

you

2.Y

ouha

veto

spec

ify

one

ofth

eop

eran

dsas

aflo

atto

gett

rue

divi

sion

,e.g

.5/2.

or5./2

(the

dot

spec

ifies

you

wan

tto

wor

kw

ithflo

at)t

oha

ve2.

5.Th

isbe

havi

oris

depr

ecat

edan

dw

illdi

sapp

ear

ina

futu

repy

thon

rele

ase

assh

own

from

the

from

__-

future__import

.

>>>

5/2

2 >>>5/2.

2.5

>>>5./2

2.5

>>>

from

__future__

import

division

>>>

5/2

2.5

>>>

5//2

2

Page 59: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 60: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

8St

ring

s

8.1

Stri

ngm

anip

ulat

ion

8.1.

1St

ring

oper

atio

ns

Equ

ality

Two

stri

ngs

are

equa

lif

and

only

ifth

eyha

veex

actly

the

sam

eco

nten

ts,

mea

ning

that

they

are

both

the

sam

ele

ngth

and

each

char

acte

rhas

aon

e-to

-one

posi

tiona

lcor

resp

onde

nce.

Man

yot

herl

angu

ages

test

strin

gson

lyfo

ride

ntity

;

53

Page 61: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

that

is,t

hey

only

test

whe

ther

two

stri

ngs

occu

pyth

esa

me

spac

ein

mem

ory.

Thi

sla

ttero

pera

tion

ispo

ssib

lein

Pyth

onus

ing

the

oper

atoris

.

Exa

mpl

e:

>>>

a=

'hello';

b=

'hello'#

Assign

'hello'

to

aand

b.

>>>

printa

==

b#

True

True

>>>

printa

==

'hello'

#True

>>>

printa

==

"hello"

#(choice

of

delimiter

is

unimportant)

True

>>>

printa

==

'hello

'#

(extra

space)

False

>>>

printa

==

'Hello'

#(wrong

case)

False

>>>

ais

a#

True

True

>>>

ais

b#

True,

because

python

caches

small

strings,

thus

stores

both

strings

in

the

same

location

True

>>>

ais

'hello'

#In

this

case

'hello'

uses

another

cache

then

variables

False

Page 62: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

'hello'

is

'hello'

#But

all

'hello's

use

the

same

cache

True

>>>

a*2

is

a*2

#No

caching

if

operations

are

applied

False

Num

eric

al

Ther

ear

etw

oqu

asi-n

umer

ical

oper

atio

nsw

hich

can

bedo

neon

strin

gs--

addi

-tio

nan

dm

ultip

licat

ion.

Strin

gad

ditio

nis

just

anot

hern

ame

forc

onca

tena

tion.

Stri

ngm

ultip

licat

ion

isre

petit

ive

addi

tion,

orco

ncat

enat

ion.

So:

>>>

c=

'a'

>>>

c+

'b'

'ab'

>>>

c*5

'aaaaa'

Page 63: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Con

tain

men

t

Ther

eis

asi

mpl

eop

erat

or'in

'tha

tret

urns

True

ifth

efir

stop

eran

dis

cont

aine

din

the

seco

nd.T

his

also

wor

kson

subs

trin

gs

>>>

x=

'hello'

>>>

y=

'ell'

>>>

xin

yFalse

>>>

yin

xTrue

Not

eth

at'p

rint

xin

y'w

ould

have

also

retu

rned

the

sam

eva

lue.

Inde

xing

and

Slic

ing

Muc

hlik

ear

rays

inot

herl

angu

ages

,the

indi

vidu

alch

arac

ters

ina

strin

gca

nbe

acce

ssed

byan

inte

gerr

epre

sent

ing

itspo

sitio

nin

the

strin

g.Th

efir

stch

arac

ter

inst

ring

sw

ould

bes[

0]an

dth

ent

hch

arac

terw

ould

beat

s[n-

1].

Page 64: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

s=

"Xanadu"

>>>

s[1]

'a'

Unl

ike

arra

ysin

othe

rlan

guag

es,P

ytho

nal

soin

dexe

sth

ear

rays

back

war

ds,

usin

gne

gativ

enu

mbe

rs.

The

last

char

acte

rha

sin

dex

-1,t

hese

cond

tola

stch

arac

terh

asin

dex

-2,a

ndso

on.

>>>

s[-4]

'n'

We

can

also

use

"slic

es"

toac

cess

asu

bstr

ing

ofs.

s[a:

b]w

illgi

veus

ast

ring

star

ting

with

s[a]

and

endi

ngw

iths[

b-1]

.

>>>

s[1:4]

'ana'

Non

eof

thes

ear

eas

sign

able

.

Page 65: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

prints

>>>

s[0]

='J'

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?TypeError:

object

does

not

support

item

assignment

>>>

s[1:3]

="up"

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?TypeError:

object

does

not

support

sliceassignment

>>>

prints

Out

puts

(ass

umin

gth

eer

rors

wer

esu

ppre

ssed

):

Xanadu

Xanadu

Ano

ther

feat

ure

ofsl

ices

isth

atif

the

begi

nnin

gor

end

isle

ftem

pty,

itw

illde

faul

tto

the

first

orla

stin

dex,

depe

ndin

gon

cont

ext:

>>>

s[2:]

Page 66: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

'nadu'

>>>

s[:3]

'Xan'

>>>

s[:]

'Xanadu'

You

can

also

use

nega

tive

num

bers

insl

ices

:

>>>

prints[-2:]

'du'

Toun

ders

tand

slic

es,i

t'sea

sies

tnot

toco

untt

heel

emen

tsth

emse

lves

.Iti

sa

bitl

ike

coun

ting

noto

nyo

urfin

gers

,but

inth

esp

aces

betw

een

them

.The

list

isin

dexe

dlik

eth

is:

Element:

12

34

Index:

01

23

-4

-3

-2

-1

Page 67: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

So,w

hen

we

ask

fort

he[1

:3]s

lice,

that

mea

nsw

est

arta

tind

ex1,

and

end

atin

dex

3,an

dta

keev

eryt

hing

inbe

twee

nth

em.I

fyou

are

used

toin

dexe

sin

Cor

Java

,thi

sca

nbe

abi

tdis

conc

ertin

gun

tilyo

uge

tuse

dto

it.

8.1.

2St

ring

cons

tant

s

Stri

ngco

nsta

nts

can

befo

und

inth

est

anda

rdst

ring

mod

ule.

Eith

ersi

ngle

ordo

uble

quot

esm

aybe

used

tode

limit

stri

ngco

nsta

nts.

8.1.

3St

ring

met

hods

The

rear

ea

num

bero

fmet

hods

orbu

ilt-i

nst

ring

func

tions

:

•ca

pita

lize

•ce

nter

•co

unt

•de

code

Page 68: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•en

code

•en

dsw

ith•

expa

ndta

bs•

find

•in

dex

•is

alnu

m•

isal

pha

•is

digi

t•

islo

wer

•is

spac

e•

istit

le•

isup

per

•jo

in•

ljust

•lo

wer

•ls

trip

•re

plac

e•

rfind

Page 69: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•ri

ndex

•rj

ust

•rs

trip

•sp

lit•

split

lines

•st

arts

with

•st

rip

•sw

apca

se•

title

•tr

ansl

ate

•up

per

•zfi

ll

Onl

yem

phas

ized

item

sw

illbe

cove

red.

Page 70: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

is*

isal

num

(),i

salp

ha()

,isd

igit(

),is

low

er()

,isu

pper

(),i

sspa

ce()

,and

istit

le()

fitin

toth

isca

tego

ry.

The

leng

thof

the

stri

ngob

ject

bein

gco

mpa

red

mus

tbe

atle

ast1

,or

the

is*

met

hods

will

retu

rnFa

lse.

Inot

herw

ords

,ast

ring

obje

ctof

len(

stri

ng)=

=0,

isco

nsid

ered

"em

pty"

,orF

alse

.

•is

alnu

mre

turn

sTr

ueif

the

stri

ngis

entir

ely

com

pose

dof

alph

abet

ican

d/or

num

eric

char

acte

rs(i

.e.n

opu

nctu

atio

n).

•is

alph

aan

dis

digi

tw

ork

sim

ilarl

yfo

ral

phab

etic

char

acte

rsor

num

eric

char

acte

rson

ly.

•is

spac

ere

turn

sTr

ueif

the

stri

ngis

com

pose

den

tirel

yof

whi

tesp

ace.

•is

low

er,i

supp

er,a

ndis

title

retu

rnTr

ueif

the

stri

ngis

inlo

wer

case

,upp

er-

case

,or

title

case

resp

ectiv

ely.

Unc

ased

char

acte

rsar

e"a

llow

ed",

such

asdi

gits

,but

ther

em

ustb

eat

leas

tone

case

dch

arac

teri

nth

est

ring

obje

ctin

orde

rto

retu

rnTr

ue.T

itlec

ase

mea

nsth

efir

stca

sed

char

acte

rofe

ach

wor

dis

uppe

rcas

e,an

dan

yim

med

iate

lyfo

llow

ing

case

dch

arac

ters

are

low

erca

se.

Page 71: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Cur

ious

ly,'

Y2K

'.ist

itle(

)ret

urns

True

.Tha

tis

beca

use

uppe

rcas

ech

arac

ters

can

only

follo

wun

case

dch

arac

ters

.Lik

ewis

e,lo

wer

case

char

acte

rsca

non

lyfo

llow

uppe

rcas

eor

low

erca

sech

arac

ters

.Hin

t:w

hite

spac

eis

unca

sed.

Exa

mpl

e:

>>>

'2YK'.istitle()

False

>>>

'Y2K'.istitle()

True

>>>

'2Y

K'.istitle()

True

title

,upp

er,l

ower

,sw

apca

se,c

apita

lize

Ret

urns

the

stri

ngco

nver

ted

totit

leca

se,u

pper

case

,low

erca

se,i

nver

tsca

se,

orca

pita

lizes

,res

pect

ivel

y.

Page 72: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

title

met

hod

capi

taliz

esth

efir

stle

tter

ofea

chw

ord

inth

est

ring

(and

mak

esth

ere

stlo

wer

case

).W

ords

are

iden

tified

assu

bstr

ings

ofal

phab

etic

char

acte

rsth

atar

ese

para

ted

byno

n-al

phab

etic

char

acte

rs,s

uch

asdi

gits

,or

whi

tesp

ace.

Thi

sca

nle

adto

som

eun

expe

cted

beha

vior

.Fo

rex

ampl

e,th

est

ring

"x1x

"w

illbe

conv

erte

dto

"X1X

"in

stea

dof

"X1x

".

The

swap

case

met

hod

mak

esal

lupp

erca

sele

tters

low

erca

sean

dvi

ceve

rsa.

The

capi

taliz

em

etho

dis

like

title

exce

ptth

atit

cons

ider

sth

een

tire

stri

ngto

bea

wor

d.(i

.e.i

tmak

esth

efir

stch

arac

teru

pper

case

and

the

rest

low

erca

se)

Exa

mpl

e:

>>>

s=

'Hello,

wOrLD'

>>>

s'Hello,

wOrLD'

>>>

s.title()

'Hello,

World'

>>>

s.swapcase()

'hELLO,

WoRld'

>>>

s.upper()

'HELLO,

WORLD'

Page 73: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

s.lower()

'hello,

world'

>>>

s.capitalize()

'Hello,

world'

coun

t

Ret

urns

the

num

bero

fthe

spec

ified

subs

trin

gsin

the

stri

ng.i

.e.

>>>

s=

'Hello,

world'

>>>

s.count('o')

#print

the

number

of

'o's

in

'Hello,

World'

(2)

2 Hin

t:.c

ount

()is

case

-sen

sitiv

e,so

this

exam

ple

will

only

coun

tthe

num

bero

flo

wer

case

lette

r'o'

s.Fo

rexa

mpl

e,if

you

ran:

>>>

s=

'HELLO,

WORLD'

>>>

s.count('o')

#print

the

number

of

lowercase

'o's

in

'HELLO,

WORLD'

(0)

0

Page 74: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

stri

p,rs

trip

,lst

rip

Ret

urns

aco

pyof

the

stri

ngw

ithth

ele

adin

g(l

stri

p)an

dtr

ailin

g(r

stri

p)w

hite

spac

ere

mov

ed.s

trip

rem

oves

both

.

>>>

s=

'\t

Hello,

world\n\t

'>>>

printsHello,

world

>>>

prints.strip()

Hello,

world

>>>

prints.lstrip()

Hello,

world

#ends

here

>>>

prints.rstrip()

Hello,

world

Not

eth

ele

adin

gan

dtr

ailin

gta

bsan

dne

wlin

es.

Stri

pm

etho

dsca

nal

sobe

used

tore

mov

eot

hert

ypes

ofch

arac

ters

.

Page 75: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

import

string

s=

'www.wikibooks.org'

print

sprint

s.strip('w')

#Removes

all

w's

from

outside

print

s.strip(string.lowercase)

#Removes

all

lowercase

letters

from

outside

print

s.strip(string.printable)

#Removes

all

printable

characters

Out

puts

:

www.wikibooks.org

.wikibooks.org

.wikibooks.

Not

eth

atst

ring

.low

erca

sean

dst

ring

.pri

ntab

lere

quir

ean

impo

rtst

ring

stat

e-m

ent

Page 76: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

ljust

,rju

st,c

ente

r

left

,rig

htor

cent

erju

stifi

esa

stri

ngin

toa

give

nfie

ldsi

ze(t

here

stis

padd

edw

ithsp

aces

).

>>>

s=

'foo'

>>>

s'foo'

>>>

s.ljust(7)

'foo

'>>>

s.rjust(7)

'foo'

>>>

s.center(7)

'foo

'

join

Join

sto

geth

erth

egi

ven

sequ

ence

with

the

stri

ngas

sepa

rato

r:

Page 77: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

seq

=['1',

'2',

'3',

'4',

'5']

>>>

''.join(seq)

'1

23

45'

>>>

'+'.join(seq)

'1+2+3+4+5'

map

may

behe

lpfu

lher

e:(i

tcon

vert

snu

mbe

rsin

seq

into

stri

ngs)

>>>

seq

=[1,2,3,4,5]

>>>

''.join(map(str,

seq))

'1

23

45'

now

arbi

trar

yob

ject

sm

aybe

inse

qin

stea

dof

just

stri

ngs.

find,

inde

x,rfi

nd,r

inde

x

The

find

and

inde

xm

etho

dsre

turn

the

inde

xof

the

first

foun

doc

curr

ence

ofth

egi

ven

subs

eque

nce.

Ifit

isno

tfou

nd,fi

ndre

turn

s-1

buti

ndex

rais

esa

Page 78: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Val

ueE

rror

.rfi

ndan

dri

ndex

are

the

sam

eas

find

and

inde

xex

cept

that

they

sear

chth

roug

hth

est

ring

from

righ

tto

left

(i.e

.the

yfin

dth

ela

stoc

curr

ence

)

>>>

s=

'Hello,

world'

>>>

s.find('l')

2 >>>

s[s.index('l'):]

'llo,

world'

>>>

s.rfind('l')

10>>>

s[:s.rindex('l')]

'Hello,

wor'

>>>

s[s.index('l'):s.rindex('l')]

'llo,

wor'

Bec

ause

Pyth

onst

ring

sac

cept

nega

tive

subs

crip

ts,i

ndex

ispr

obab

lybe

tter

used

insi

tuat

ions

like

the

one

show

nbe

caus

eus

ing

find

inst

ead

wou

ldyi

eld

anun

inte

nded

valu

e.

Page 79: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

repl

ace

Rep

lace

wor

ksju

stlik

eit

soun

ds.

Itre

turn

sa

copy

ofth

est

ring

with

all

occu

rren

ces

ofth

efir

stpa

ram

eter

repl

aced

with

the

seco

ndpa

ram

eter

.

>>>

'Hello,

world'.replace('o',

'X')

'HellX,

wXrld'

Or,

usin

gva

riab

leas

sign

men

t:

string

='Hello,

world'

newString

=string.replace('o',

'X')

print

string

print

newString

Out

puts

:

Hello,

world

HellX,

wXrld

Page 80: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Not

ice,

the

orig

inal

vari

able

(string

)re

mai

nsun

chan

ged

afte

rth

eca

llto

replace

.

expa

ndta

bs

Rep

lace

sta

bsw

ithth

eap

prop

riate

num

bero

fspa

ces

(def

ault

num

bero

fspa

ces

pert

ab=

8;th

isca

nbe

chan

ged

bypa

ssin

gth

eta

bsi

zeas

anar

gum

ent)

.

s=

'abcdefg\tabc\ta'

print

sprint

len(s)

t=

s.expandtabs()

print

tprint

len(t)

Out

puts

:

Page 81: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

abcdefg

abc

a13

abcdefg

abc

a17

Not

ice

how

(alth

ough

thes

ebo

thlo

okth

esa

me)

the

seco

ndst

ring

(t)

has

adi

ffer

entl

engt

hbe

caus

eea

chta

bis

repr

esen

ted

bysp

aces

nott

abch

arac

ters

.

Tous

ea

tab

size

of4

inst

ead

of8:

v=

s.expandtabs(4)

print

vprint

len(v)

Out

puts

:

abcdefg

abc

a13

Page 82: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Plea

seno

teea

chta

bis

not

alw

ays

coun

ted

asei

ght

spac

es.

Rat

her

ata

b"p

ushe

s"th

eco

untt

oth

ene

xtm

ultip

leof

eigh

t.Fo

rexa

mpl

e:

s=

'\t\t'

print

s.expandtabs().replace('

',

'*')

print

len(s.expandtabs())

Out

put:

****************

16

s=

'abc\tabc\tabc'

print

s.expandtabs().replace('

',

'*')

print

len(s.expandtabs())

Out

puts

:

Page 83: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

abc*****abc*****abc

19

split

,spl

itlin

es

The

split

met

hod

retu

rns

alis

toft

hew

ords

inth

est

ring.

Itca

nta

kea

sepa

rato

rar

gum

entt

ous

ein

stea

dof

whi

tesp

ace.

>>>

s=

'Hello,

world'

>>>

s.split()

['Hello,',

'world']

>>>

s.split('l')

['He',

'',

'o,

wor',

'd']

Not

eth

atin

neith

erca

seis

the

sepa

rato

rinc

lude

din

the

split

strin

gs,b

utem

pty

stri

ngs

are

allo

wed

.

Page 84: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

split

lines

met

hod

brea

ksa

mul

tilin

est

ring

into

man

ysi

ngle

line

stri

ngs.

Itis

anal

ogou

sto

split

('\n'

)(b

utac

cept

s'\r

'and

'\r\n

'as

delim

iters

asw

ell)

exce

ptth

atif

the

strin

gen

dsin

ane

wlin

ech

arac

ter,

split

lines

igno

res

that

final

char

acte

r(se

eex

ampl

e).

>>>

s=

"""

...

One

line

...

Two

lines

...

Red

lines

...

Blue

lines

...

Green

lines

...

"""

>>>

s.split('\n')

['',

'One

line',

'Two

lines',

'Red

lines',

'Blue

lines',

'Green

lines',

'']

>>>

s.splitlines()

['',

'One

line',

'Two

lines',

'Red

lines',

'Blue

lines',

'Green

lines']

Page 85: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 86: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9L

ists

9.1

Abo

utlis

tsin

Pyth

on

Alis

tin

Pyth

onis

anor

dere

dgr

oup

ofite

ms

(ore

lem

ents

).It

isa

very

gene

ral

stru

ctur

e,an

dlis

tele

men

tsdo

n'th

ave

tobe

ofth

esa

me

type

.For

inst

ance

,you

coul

dpu

tnum

bers

,let

ters

,and

stri

ngs

allo

nth

esa

me

list.

Ifyo

uar

eus

ing

am

oder

nve

rsio

nof

Pyth

on(a

ndyo

ush

ould

be),

ther

eis

acl

ass

calle

d'li

st'.

Ifyo

uw

ish,

you

can

mak

eyo

urow

nsu

bcla

ssof

it,an

dde

term

ine

listb

ehav

iour

whi

chis

diff

eren

ttha

nth

ede

faul

tsta

ndar

d.B

utfir

st,

you

shou

ldbe

fam

iliar

with

the

curr

entb

ehav

iour

oflis

ts.

79

Page 87: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9.1.

1L

istn

otat

ion

The

rear

etw

odi

ffer

entw

ays

tom

ake

alis

tin

Pyth

on.

The

first

isth

roug

has

sign

men

t("s

tatic

ally

"),t

hese

cond

isus

ing

listc

ompr

ehen

sion

s("a

ctiv

ely"

).

Tom

ake

ast

atic

listo

fite

ms,

writ

eth

embe

twee

nsq

uare

brac

kets

.For

exam

ple:

[1,2,3,"This

is

alist",'c',Donkey("kong")

]

Aco

uple

ofth

ings

tolo

okat

.

1.T

here

are

diff

eren

tdat

aty

pes

here

.Lis

tsin

Pyth

onm

ayco

ntai

nm

ore

than

one

data

type

.2.

Obj

ects

can

becr

eate

d'o

nth

efly

'and

adde

dto

lists

.The

last

item

isa

new

kind

ofD

onke

y.

Wri

ting

lists

this

way

isve

ryqu

ick

(and

obvi

ous)

.How

ever

,itd

oes

nott

ake

into

acco

untt

hecu

rren

tsta

teof

anyt

hing

else

.The

othe

rway

tom

ake

alis

tis

tofo

rmit

usin

glis

tcom

preh

ensi

on.T

hatm

eans

you

actu

ally

desc

ribe

the

Page 88: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

proc

ess.

Todo

that

,the

listi

sbr

oken

into

two

piec

es.T

hefir

stis

api

ctur

eof

wha

teac

hel

emen

twill

look

like,

and

the

seco

ndis

wha

tyou

doto

geti

t.

Fori

nsta

nce,

lets

say

we

have

alis

tofw

ords

:

listOfWords

=["this","is","a","list","of","words"]

Lis

tcom

preh

ensi

ons

-->

see

also

Tips

and

Tric

ks1

We

will

take

the

first

lette

rof

each

wor

dan

dm

ake

alis

tou

tof

it(u

sing

so-c

alle

dlis

tcom

preh

ensi

on).

>>>

listOfWords

=["this","is","a","list","of","words"]

>>>

items

=[

word[0]

forword

in

listOfWords

]

1http://en.wikibooks.org/wiki/Python%20Programming%2FTips_

and_Tricks%23List_comprehension_and_generators

Page 89: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

printitems

['t',

'i',

'a',

'l',

'o',

'w']

Lis

tcom

preh

ensi

onal

low

syo

uto

use

mor

eth

anon

efo

rst

atem

ent.

Itw

illev

alua

teth

eite

ms

inal

lof

the

obje

cts

sequ

entia

llyan

dw

illlo

opov

erth

esh

orte

robj

ects

ifon

eob

ject

islo

nger

than

the

rest

.

>>>

item

=[x+y

forx

in

'flower'

fory

in

'pot']

>>>

printitem

['fp',

'fo',

'ft',

'lp',

'lo',

'lt',

'op',

'oo',

'ot',

'wp',

'wo',

'wt',

'ep',

'eo',

'et',

'rp',

'ro',

'rt']

Lis

tcom

preh

ensi

onal

soal

low

syo

uto

use

anif

stat

emen

t,to

only

incl

ude

mem

bers

into

the

listt

hatf

ulfil

lace

rtai

nco

nditi

on.W

eca

nth

usex

clud

eal

lca

ses

whe

rex

iseq

ualt

ow

and

yis

equa

lto

o;or

we

can

only

excl

ude

the

case

whe

rex

iseq

ualt

ow

and

yis

equa

lto

o(a

ndth

usre

mov

ing

the

'wo'

from

the

list)

.

>>>

print[x+yfor

xin

'flower'

fory

in

'pot']

['fp',

'fo',

'ft',

'lp',

'lo',

'lt',

'op',

'oo',

'ot',

'wp',

'wo',

Page 90: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

'wt',

'ep',

'eo',

'et',

'rp',

'ro',

'rt']

>>>

print[x+yfor

xin

'flower'

fory

in

'pot'

ifx

!=

'w'

and

y!=

'o'

]['fp',

'ft',

'lp',

'lt',

'op',

'ot',

'ep',

'et',

'rp',

'rt']

>>>

print[x+yfor

xin

'flower'

fory

in

'pot'

ifx

!=

'w'

or

y!=

'o'

]['fp',

'fo',

'ft',

'lp',

'lo',

'lt',

'op',

'oo',

'ot',

'wp',

'wt',

'ep',

'eo',

'et',

'rp',

'ro',

'rt']

Pyth

on's

listc

ompr

ehen

sion

does

notd

efine

asc

ope.

Any

vari

able

sth

atar

ebo

und

inan

eval

uatio

nre

mai

nbo

und

tow

hate

vert

hey

wer

ela

stbo

und

tow

hen

the

eval

uatio

nw

asco

mpl

eted

:

>>>

printx,

yr

t

Thi

sis

exac

tlyth

esa

me

asif

the

com

preh

ensi

onha

dbe

enex

pand

edin

toan

expl

icitl

y-ne

sted

grou

pof

one

orm

ore

'for'

stat

emen

tsan

d0

orm

ore

'if'

stat

emen

ts.

Page 91: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Lis

tcre

atio

nsh

ortc

uts

Pyth

onpr

ovid

esa

shor

tcut

toin

itial

ize

alis

tto

apa

rtic

ular

size

and

with

anin

itial

valu

efo

reac

hel

emen

t:

>>>

zeros=[0]*5

>>>

printzeros

[0,

0,

0,

0,

0]

Thi

sw

orks

fora

nyda

taty

pe:

>>>

foos=['foo']*8

>>>

printfoos

['foo',

'foo',

'foo',

'foo',

'foo',

'foo',

'foo',

'foo']

with

aca

veat

.Whe

nbu

ildin

ga

new

listb

ym

ultip

lyin

g,Py

thon

copi

esea

chite

mby

refe

renc

e.T

his

pose

sa

prob

lem

form

utab

leite

ms,

fori

nsta

nce

ina

mul

tidim

ensi

onal

arra

yw

here

each

elem

enti

sits

elfa

list.

You'

dgu

ess

that

the

easy

way

toge

nera

tea

two

dim

ensi

onal

arra

yw

ould

be:

Page 92: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

listoflists=[

[0]*4

]*5

and

this

wor

ks,b

utpr

obab

lydo

esn'

tdo

wha

tyou

expe

ct:

>>>

listoflists=[

[0]*4

]*5

>>>

printlistoflists

[[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0]]

>>>

listoflists[0][2]=1

>>>

printlistoflists

[[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0]]

Wha

t'sha

ppen

ing

here

isth

atPy

thon

isus

ing

the

sam

ere

fere

nce

toth

ein

ner

lista

sth

eel

emen

tsof

the

oute

rlis

t.A

noth

erw

ayof

look

ing

atth

isis

sue

isto

exam

ine

how

Pyth

onse

esth

eab

ove

defin

ition

:

>>>

innerlist=[0]*4

>>>

listoflists=[innerlist]*5

>>>

printlistoflists

Page 93: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

[[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0]]

>>>

innerlist[2]=1

>>>

printlistoflists

[[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0],

[0,

0,

1,

0]]

Ass

umin

gth

eab

ove

effe

ctis

notw

haty

ouin

tend

,one

way

arou

ndth

isis

sue

isto

use

listc

ompr

ehen

sion

s:

>>>

listoflists=[[0]*4fori

in

range(5)]

>>>

printlistoflists

[[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0]]

>>>

listoflists[0][2]=1

>>>

printlistoflists

[[0,

0,

1,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0],

[0,

0,

0,

0]]

Page 94: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9.1.

2O

pera

tions

onlis

ts

Lis

tAtt

ribu

tes

Tofin

dth

ele

ngth

ofa

listu

seth

ebu

iltin

len(

)met

hod.

>>>

len([1,2,3])

3 >>>

a=

[1,2,3,4]

>>>

len(

a)

4 Com

bini

nglis

ts

Lis

tsca

nbe

com

bine

din

seve

ralw

ays.

The

easi

esti

sju

stto

'add

'the

m.F

orin

stan

ce:

Page 95: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

[1,2]

+[3,4]

[1,

2,

3,

4]

Ano

ther

way

toco

mbi

nelis

tsis

with

exte

nd.

Ifyo

une

edto

com

bine

lists

insi

deof

ala

mbd

a,ex

tend

isth

ew

ayto

go.

>>>

a=

[1,2,3]

>>>

b=

[4,5,6]

>>>

a.extend(b)

>>>

printa

[1,

2,

3,

4,

5,

6]

The

othe

rway

toap

pend

ava

lue

toa

listi

sto

use

appe

nd.F

orex

ampl

e:

>>>

p=[1,2]

>>>

p.append([3,4])

>>>

p[1,

2,

[3,

4]]

>>>

#or

>>>

printp

[1,

2,

[3,

4]]

Page 96: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

How

ever

,[3,

4]is

anel

emen

toft

helis

t,an

dno

tpar

toft

helis

t.ap

pend

alw

ays

adds

one

elem

ento

nly

toth

een

dof

alis

t.So

ifth

ein

tent

ion

was

toco

ncat

enat

etw

olis

ts,a

lway

sus

eex

tend

.

Get

ting

piec

esof

lists

(slic

es)

Con

tinuo

ussl

ices

Lik

est

ring

s2 ,lis

tsca

nbe

inde

xed

and

slic

ed.

>>>

list

=[2,

4,

"usurp",

9.0,"n"]

>>>

list[2]

'usurp'

>>>

list[3:]

[9.0,

'n']

2C

hapt

er8

onpa

ge53

Page 97: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Muc

hlik

eth

esl

ice

ofa

strin

gis

asu

bstri

ng,t

hesl

ice

ofa

listi

sa

list.

How

ever

,lis

tsdi

ffer

from

stri

ngs

inth

atw

eca

nas

sign

new

valu

esto

the

item

sin

alis

t.

>>>

list[1]

=17

>>>

list

[2,

17,

'usurp',

9.0,'n']

We

can

even

assi

gnne

wva

lues

tosl

ices

ofth

elis

ts,w

hich

don'

teve

nha

veto

beth

esa

me

leng

th

>>>

list[1:4]

=["opportunistic",

"elk"]

>>>

list

[2,

'opportunistic',

'elk',

'n']

It's

even

poss

ible

toap

pend

thin

gson

toth

een

dof

lists

byas

sign

ing

toan

empt

ysl

ice:

>>>

list[:0]

=[3.14,2.71]

>>>

list

[3.14,

2.71,

2,

'opportunistic',

'elk',

'n']

Page 98: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

You

can

also

com

plet

ely

chan

geco

nten

tsof

alis

t:

>>>

list[:]

=['new',

'list',

'contents']

>>>

list

['new',

'list',

'contents']

On

the

righ

t-ha

ndsi

deof

assi

gnm

ents

tate

men

tcan

bean

yite

rabl

ety

pe:

>>>

list[:2]

=('element',('t',),[])

>>>

list

['element',

('t',),

[],

'contents']

With

slic

ing

you

can

crea

teco

pyof

listb

ecau

sesl

ice

retu

rns

ane

wlis

t:

>>>

original

=[1,

'element',

[]]

>>>

list_copy

=original[:]

>>>

list_copy

[1,

'element',

[]]

>>>

list_copy.append('new

element')

>>>

list_copy

[1,

'element',

[],

'new

element']

Page 99: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

original

[1,

'element',

[]]

butt

his

issh

allo

wco

pyan

dco

ntai

nsre

fere

nces

toel

emen

tsfr

omor

igin

allis

t,so

beca

refu

lwith

mut

able

type

s:

>>>

list_copy[2].append('something')

>>>

original

[1,

'element',

['something']]

Non

-Con

tinuo

ussl

ices

Itis

also

poss

ible

toge

tnon

-con

tinuo

uspa

rts

ofan

arra

y.If

one

wan

ted

toge

tev

ery

n-th

occu

rren

ceof

alis

t,on

ew

ould

use

the

::op

erat

or.

The

synt

axis

a:b:

nw

here

aan

db

are

the

star

tand

end

ofth

esl

ice

tobe

oper

ated

upon

.

>>>

list

=[ifor

iin

range(10)

]>>>

list

Page 100: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

[0,

1,

2,

3,

4,

5,

6,

7,

8,

9]

>>>

list[::2]

[0,

2,

4,

6,

8]

>>>

list[1:7:2]

[1,

3,

5]

Com

pari

nglis

ts

Lis

tsca

nbe

com

pare

dfo

requ

ality

.

>>>

[1,2]

==

[1,2]

True

>>>

[1,2]

==

[3,4]

False

Sort

ing

lists

Sort

ing

lists

isea

syw

itha

sort

met

hod.

Page 101: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

list

=[2,

3,

1,

'a',

'b']

>>>

list.sort()

>>>

list

[1,

2,

3,

'a',

'b']

Not

eth

atth

elis

tis

sort

edin

plac

e,an

dth

eso

rt()

met

hod

retu

rns

Non

eto

emph

asiz

eth

issi

deef

fect

.

Ifyo

uus

ePy

thon

2.4

orhi

gher

ther

ear

eso

me

mor

eso

rtpa

ram

eter

s:

sort

(cm

p,ke

y,re

vers

e)

cmp

:met

hod

tobe

used

fors

ortin

gke

y:f

unct

ion

tobe

exec

uted

with

key

ele-

men

t.Li

stis

sorte

dby

retu

rn-v

alue

ofth

efu

nctio

nre

vers

e:s

ort(r

ever

se=T

rue)

orso

rt(r

ever

se=F

alse

)

Pyth

onal

soin

clud

esa

sort

ed()

func

tion.

>>>

list

=[5,

2,

3,

'q',

'p']

>>>

sorted(list)

[2,

3,

5,

'p',

'q']

Page 102: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

list

[5,

2,

3,

'q',

'p']

Not

eth

atun

like

the

sort

()m

etho

d,so

rted

(lis

t)do

esno

tsor

tthe

listi

npl

ace,

buti

nste

adre

turn

sth

eso

rted

list.

The

sorte

d()f

unct

ion,

like

the

sort(

)met

hod

also

acce

pts

the

reve

rse

para

met

er.

9.2

Lis

tmet

hods

9.2.

1ap

pend

(x)

Add

item

xon

toth

een

dof

the

list.

>>>

list

=[1,

2,

3]

>>>

list.append(4)

>>>

list

[1,

2,

3,

4]

Page 103: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

See

pop(

i)3

9.2.

2po

p(i)

Rem

ove

the

item

inth

elis

tatt

hein

dex

iand

retu

rnit.

Ifii

sno

tgiv

en,r

emov

eth

eth

ela

stite

min

the

lista

ndre

turn

it.

>>>

list

=[1,

2,

3,

4]

>>>

a=

list.pop(0)

>>>

list

[2,

3,

4]

>>>

a1 >>>

b=

list.pop()

>>>list

[2,

3]

>>>

b4 3

Cha

pter

9.2.

2on

page

96

Page 104: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9.3

oper

ator

s

9.3.

1in

the

oper

ator

'in'i

sus

edfo

rtw

opu

rpos

eset

hert

oite

rate

over

ever

yite

min

alis

tin

afo

rloo

por

toch

eck

ifa

valu

eis

ina

listr

etun

ing

true

orfa

lse.

>>>

list

=[1,

2,

3,

4]

>>>

if3

in

list:

>>>

....

>>>

l=

[0,

1,

2,

3,

4]

>>>

3in

lTrue

>>>

18

in

lFalse

}}

Page 105: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 106: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

10D

ictio

nari

es

10.1

Abo

utdi

ctio

nari

esin

Pyth

on

Adi

ctio

nary

inpy

thon

isa

colle

ctio

nof

unor

dere

dva

lues

whi

char

eac

cess

edby

key.

10.1

.1D

ictio

nary

nota

tion

Dic

tiona

riesm

aybe

crea

ted

dire

ctly

orco

nver

ted

from

sequ

ence

s.D

ictio

narie

sar

een

clos

edin

curl

ybr

aces

,{}

99

Page 107: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

d=

{'city':'Paris',

'age':38,

(102,1650,1601):'A

matrix

coordinate'}

>>>

seq

=[('city','Paris'),

('age',

38),

((102,1650,1601),'A

matrix

coordinate')]

>>>

d{'city':

'Paris',

'age':

38,

(102,

1650,

1601):

'A

matrix

coordinate'}

>>>

dict(seq)

{'city':

'Paris',

'age':

38,

(102,

1650,

1601):

'A

matrix

coordinate'}

>>>

d==

dict(seq)

True

Als

o,di

ctio

nari

esca

nbe

easi

lycr

eate

dby

zipp

ing

two

sequ

ence

s.

>>>

seq1

=('a','b','c','d')

>>>

seq2

=[1,2,3,4]

>>>

d=

dict(zip(seq1,seq2))

>>>

d{'a':

1,

'c':

3,

'b':

2,

'd':

4}

Page 108: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

10.1

.2O

pera

tions

onD

ictio

nari

es

The

oper

atio

nson

dict

iona

ries

are

som

ewha

tuni

que.

Slic

ing

isno

tsup

port

ed,

sinc

eth

eite

ms

have

noin

trin

sic

orde

r.

>>>

d=

{'a':1,'b':2,

'cat':'Fluffers'}

>>>

d.keys()

['a',

'b',

'cat']

>>>

d.values()

[1,

2,

'Fluffers']

>>>

d['a']

1 >>>

d['cat']

='Mr.

Whiskers'

>>>

d['cat']

'Mr.

Whiskers'

>>>

'cat'

in

dTrue

>>>

'dog'

in

dFalse

Page 109: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

10.1

.3C

ombi

ning

two

Dic

tiona

ries

You

can

com

bine

two

dict

iona

ries

byus

ing

the

upda

tem

etho

dof

the

prim

ary

dict

iona

ry.N

ote

that

the

upda

tem

etho

dw

illm

erge

exis

ting

elem

ents

ifth

eyco

nflic

t.

>>>

d=

{'apples':

1,

'oranges':

3,

'pears':

2}

>>>

ud

={'pears':

4,

'grapes':

5,

'lemons':

6}

>>>

d.update(ud)

>>>

d{'grapes':

5,

'pears':

4,

'lemons':

6,

'apples':

1,

'oranges':

3}

>>>

10.1

.4D

elet

ing

from

dict

iona

ry

del

dictionaryName[membername]

Page 110: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

11Se

ts

Pyth

onal

soha

san

impl

emen

tatio

nof

the

mat

hem

atic

alse

t1 .Unl

ike

sequ

ence

obje

cts

such

aslis

tsan

dtu

ples

,in

whi

chea

chel

emen

tis

inde

xed,

ase

tis

anun

orde

red

colle

ctio

nof

obje

cts.

Sets

also

cann

otha

vedu

plic

ate

mem

bers

-agi

ven

obje

ctap

pear

sin

ase

t0or

1tim

es.F

orm

ore

info

rmat

ion

onse

ts,s

eeth

eSe

tThe

ory2

wik

iboo

k.Se

tsal

sore

quir

eth

atal

lmem

bers

ofth

ese

tbe

hash

able

.Any

obje

ctth

atca

nbe

used

asa

dict

iona

ryke

yca

nbe

ase

tmem

ber.

1http://en.wikipedia.org/wiki/set%20

2http://en.wikibooks.org/wiki/Set%20Theory

103

Page 111: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Inte

gers

,floa

ting

poin

tnum

bers

,tup

les,

and

stri

ngs

are

hash

able

;dic

tiona

ries

,lis

ts,a

ndot

hers

ets

(exc

eptf

roze

nset

s3 )are

not.

11.0

.5C

onst

ruct

ing

Sets

One

way

toco

nstr

uct

sets

isby

pass

ing

any

sequ

entia

lob

ject

toth

e"s

et"

cons

truc

tor.

>>>

set([0,

1,

2,

3])

set([0,

1,

2,

3])

>>>

set("obtuse")

set(['b',

'e',

'o',

's',

'u',

't'])

We

can

also

add

elem

ents

tose

tson

eby

one,

usin

gth

e"a

dd"

func

tion.

>>>

s=

set([12,

26,

54])

>>>

s.add(32)

3C

hapt

er11

.0.1

1on

page

115

Page 112: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

sset([32,

26,

12,

54])

Not

eth

atsi

nce

ase

tdoe

sno

tcon

tain

dupl

icat

eel

emen

ts,i

fw

ead

don

eof

the

mem

bers

ofs

tos

agai

n,th

ead

dfu

nctio

nw

illha

veno

effe

ct.T

his

sam

ebe

havi

oroc

curs

inth

e"u

pdat

e"fu

nctio

n,w

hich

adds

agr

oup

ofel

emen

tsto

ase

t.

>>>

s.update([26,

12,

9,

14])

>>>

sset([32,

9,

12,

14,

54,

26])

Not

eth

atyo

uca

ngi

vean

yty

peof

sequ

entia

lstr

uctu

re,o

reve

nan

othe

rset

,to

the

upda

tefu

nctio

n,re

gard

less

ofw

hats

truc

ture

was

used

toin

itial

ize

the

set.

The

setf

unct

ion

also

prov

ides

aco

pyco

nstru

ctor

.How

ever

,rem

embe

rtha

tthe

copy

cons

truc

torw

illco

pyth

ese

t,bu

tnot

the

indi

vidu

alel

emen

ts.

>>>

s2

=s.copy()

Page 113: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

s2

set([32,

9,

12,

14,

54,

26])

11.0

.6M

embe

rshi

pTe

stin

g

We

can

chec

kif

anob

ject

isin

the

setu

sing

the

sam

e"i

n"op

erat

oras

with

sequ

entia

ldat

aty

pes.

>>>

32

in

sTrue

>>>

6in

sFalse

>>>

6not

in

sTrue

We

can

also

test

the

mem

bers

hip

ofen

tire

sets

.Giv

entw

ose

tsS 1

and

S 2,w

ech

eck

ifS 1

isa

subs

et4

ora

supe

rset

ofS 2

.

4http://en.wikipedia.org/wiki/Subset

Page 114: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

s.issubset(set([32,

8,

9,

12,

14,

-4,

54,

26,

19]))

True

>>>

s.issuperset(set([9,

12]))

True

Not

eth

at"i

ssub

set"

and

"iss

uper

set"

can

also

acce

ptse

quen

tiald

ata

type

sas

argu

men

ts

>>>

s.issuperset([32,

9])

True

Not

eth

atth

e<=

and

>=op

erat

ors

also

expr

ess

the

issu

bset

and

issu

pers

etfu

nctio

nsre

spec

tivel

y.

>>>

set([4,

5,

7])

<=

set([4,

5,

7,

9])

True

>>>

set([9,

12,

15])

>=

set([9,

12])

True

Page 115: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Lik

elis

ts,t

uple

s,an

dst

ring

,we

can

use

the

"len

"fu

nctio

nto

find

the

num

ber

ofite

ms

ina

set.

11.0

.7R

emov

ing

Item

s

Ther

ear

eth

ree

func

tions

whi

chre

mov

ein

divi

dual

item

sfr

oma

set,

calle

dpo

p,re

mov

e,an

ddi

scar

d.Th

efir

st,p

op,s

impl

yre

mov

esan

item

from

the

set.

Not

eth

atth

ere

isno

defin

edbe

havi

oras

tow

hich

elem

enti

tcho

oses

tore

mov

e.

>>>

s=

set([1,2,3,4,5,6])

>>>

s.pop()

1 >>>

sset([2,3,4,5,6])

We

also

have

the

"rem

ove"

func

tion

tore

mov

ea

spec

ified

elem

ent.

>>>

s.remove(3)

Page 116: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

sset([2,4,5,6])

How

ever

,rem

ovin

ga

item

whi

chis

n'ti

nth

ese

tcau

ses

aner

ror.

>>>

s.remove(9)

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?KeyError:

9

Ifyo

uw

ish

toav

oid

this

erro

r,us

e"d

isca

rd."

Itha

sth

esa

me

func

tiona

lity

asre

mov

e,bu

twill

sim

ply

dono

thin

gif

the

elem

enti

sn't

inth

ese

t

We

also

have

anot

hero

pera

tion

forr

emov

ing

elem

ents

from

ase

t,cl

ear,

whi

chsi

mpl

yre

mov

esal

lele

men

tsfr

omth

ese

t.

>>>

s.clear()

>>>

sset([])

Page 117: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

11.0

.8It

erat

ion

Ove

rSe

ts

We

can

also

have

alo

opm

ove

over

each

ofth

eite

ms

ina

set.

How

ever

,sin

cese

tsar

eun

orde

red,

itis

unde

fined

whi

chor

dert

heite

ratio

nw

illfo

llow

.

>>>

s=

set("blerg")

>>>

forn

in

s:

...

printn,

...

rb

el

g

11.0

.9Se

tOpe

ratio

ns

Pyth

onal

low

sus

tope

rfor

mal

lth

est

anda

rdm

athe

mat

ical

set

oper

atio

ns,

usin

gm

embe

rsof

set.

Not

eth

atea

chof

thes

ese

tope

ratio

nsha

sse

vera

lfor

ms.

One

ofth

ese

form

s,s1

.func

tion(

s2)

will

retu

rnan

othe

rse

twhi

chis

crea

ted

by"f

unct

ion"

appl

ied

toS 1

and

S 2.

The

othe

rfo

rm,s

1.fu

nctio

n_up

date

(s2)

,w

illch

ange

S 1to

beth

ese

tcre

ated

by"f

unct

ion"

ofS 1

and

S 2.F

inal

ly,s

ome

Page 118: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

func

tions

have

equi

vale

ntsp

ecia

lope

rato

rs.F

orex

ampl

e,s1

&s2

iseq

uiva

lent

tos1

.inte

rsec

tion(

s2)

Uni

on

The

unio

n5is

the

mer

gero

ftw

ose

ts.A

nyel

emen

tin

S 1or

S 2w

illap

pear

inth

eiru

nion

.

>>>

s1

=set([4,

6,

9])

>>>

s2

=set([1,

6,

8])

>>>

s1.union(s2)

set([1,

4,

6,

8,

9])

>>>

s1

|s2

set([1,

4,

6,

8,

9])

Not

eth

atun

ion'

sup

date

func

tion

issi

mpl

y"u

pdat

e"ab

ove6 .

5http://en.wikipedia.org/wiki/union_%28set_theory%29

6C

hapt

er11

.0.5

onpa

ge10

4

Page 119: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Inte

rsec

tion

Any

elem

entw

hich

isin

both

S 1an

dS 2

will

appe

arin

thei

rint

erse

ctio

n7 .

>>>

s1

=set([4,

6,

9])

>>>

s2

=set([1,

6,

8])

>>>

s1.intersection(s2)

set([6])

>>>

s1

&s2

set([6])

>>>

s1.intersection_update(s2)

>>>

s1

set([6])

7http://en.wikipedia.org/wiki/intersection_%28set_theory%29

Page 120: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Sym

met

ric

Diff

eren

ce

The

sym

met

ric

diff

eren

ce8

oftw

ose

tsis

the

seto

fele

men

tsw

hich

are

inon

eof

eith

erse

t,bu

tnot

inbo

th.

>>>

s1

=set([4,

6,

9])

>>>

s2

=set([1,

6,

8])

>>>

s1.symmetric_difference(s2)

set([8,

1,

4,

9])

>>>

s1

^s2

set([8,

1,

4,

9])

>>>

s1.symmetric_difference_update(s2)

>>>

s1

set([8,

1,

4,

9])

8http://en.wikipedia.org/wiki/symmetric_difference

Page 121: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

SetD

iffer

ence

Pyth

onca

nal

sofin

dth

ese

tdiff

eren

ce9

ofS 1

and

S 2,w

hich

isth

eel

emen

tsth

atar

ein

S 1bu

tnot

inS 2

.

>>>

s1

=set([4,

6,

9])

>>>

s2

=set([1,

6,

8])

>>>

s1.difference(s2)

set([9,

4])

>>>

s1

-s2

set([9,

4])

>>>

s1.difference_update(s2)

>>>

s1

set([9,

4])

9http://en.wikipedia.org/wiki/Complement_%28set_theory%29%

23Relative_Complement

Page 122: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

11.0

.10

Mul

tiple

sets

Star

ting

with

Pyth

on2.

6,"u

nion

","i

nter

sect

ion"

,an

d"d

iffer

ence

"ca

nw

ork

with

mul

tiple

inpu

tby

usin

gth

ese

tco

nstr

ucto

r.Fo

rex

ampl

e,us

ing

"set

.inte

rsec

tion(

)":

>>>

s1

=set([3,

6,

7,

9])

>>>

s2

=set([6,

7,

9,

10])

>>>

s3

=set([7,

9,

10,

11])

>>>

set.intersection(s1,

s2,

s3)

set([9,

7])

11.0

.11

froz

ense

t

Afr

ozen

seti

sba

sica

llyth

esa

me

asa

set,

exce

ptth

atit

isim

mut

able

-onc

eit

iscr

eate

d,its

mem

bers

cann

otbe

chan

ged.

Sinc

eth

eyar

eim

mut

able

,the

yar

eal

soha

shab

le,w

hich

mea

nsth

atfr

ozen

sets

can

beus

edas

mem

bers

inot

her

sets

and

asdi

ctio

nary

keys

.fro

zens

ets

have

the

sam

efu

nctio

nsas

norm

alse

ts,

Page 123: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

exce

ptno

neof

the

func

tions

that

chan

geth

eco

nten

ts(u

pdat

e,re

mov

e,po

p,et

c.)

are

avai

labl

e.

>>>

fs

=frozenset([2,

3,

4])

>>>

s1

=set([fs,

4,

5,

6])

>>>

s1

set([4,

frozenset([2,

3,

4]),

6,

5])

>>>

fs.intersection(s1)

frozenset([4])

>>>

fs.add(6)

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

<module>

AttributeError:

'frozenset'

object

has

no

attribute

'add'

11.0

.12

Ref

eren

ce

Pyth

onL

ibra

ryR

efer

ence

onSe

tTyp

es10

10http://docs.python.org/library/stdtypes.html#

set-types-set-frozenset

Page 124: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

12O

pera

tors

12.1

Bas

ics

Pyth

onm

ath

wor

kslik

eyo

uw

ould

expe

ct.

>>>

x=

2>>>

y=

3>>>

z=

5>>>

x*y

6 >>>

x+

y5

117

Page 125: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

x*y

+z

11>>>

(x

+y)

*z

25 Not

eth

atPy

thon

adhe

res

toth

ePE

MD

AS

orde

rofo

pera

tions

1 .

12.2

Pow

ers

The

reis

abu

iltin

expo

nent

iatio

nop

erat

or**

,whi

chca

nta

keei

ther

inte

gers

,flo

atin

gpo

into

rcom

plex

num

bers

.Thi

soc

cupi

esits

prop

erpl

ace

inth

eor

der

ofop

erat

ions

.

>>>

2**8

256

1http://en.wikipedia.org/wiki/Order%20of%20operations%20

Page 126: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

12.3

Div

isio

nan

dTy

peC

onve

rsio

n

ForP

ytho

n2.

x,di

vidi

ngtw

oin

tege

rsor

long

suse

sint

eger

divi

sion

,als

okn

own

as"fl

oord

ivis

ion"

(app

lyin

gth

eflo

orfu

nctio

n2af

terd

ivis

ion.

So,f

orex

ampl

e,5

/2is

2.U

sing

"/"

todo

divi

sion

this

way

isde

prec

ated

;if

you

wan

tfloo

rdi

visi

on,u

se"/

/"(a

vaila

ble

inPy

thon

2.2

and

late

r).

"/"

does

"tru

edi

visi

on"

forfl

oats

and

com

plex

num

bers

;for

exam

ple,

5.0/

2.0

is2.

5.

ForP

ytho

n3.

x,"/

"do

es"t

rue

divi

sion

"fo

rall

type

s.34

2http://en.wikipedia.org/wiki/Floor%20function

3[http://www.python.org/doc/2.2.3/whatsnew/node7.html

Wha

t'sN

ewin

Pyth

on2.

24

PEP

238

--C

hang

ing

the

Div

isio

nO

pera

tor

ˆ{http://www.python.org/dev/

peps/pep-0238/}

Page 127: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Div

idin

gby

orin

toa

float

ing

poin

tnum

ber

(the

rear

eno

frac

tiona

ltyp

esin

Pyth

on)w

illca

use

Pyth

onto

use

true

divi

sion

.To

coer

cean

inte

gert

obe

com

ea

float

,'flo

at()

'with

the

inte

gera

sa

para

met

er

>>>

x=

5>>>

float(x)

5.0

Thi

sca

nbe

gene

raliz

edfo

roth

ernu

mer

icty

pes:

int(

),co

mpl

ex()

,lon

g().

Bew

are

that

due

toth

elim

itatio

nsof

float

ing

poin

tar

ithm

etic

5 ,ro

undi

nger

rors

can

caus

eun

expe

cted

resu

lts.F

orex

ampl

e:

>>>

print

0.6/0.2

3.0

>>>

print

0.6//0.2

2.0

5http://en.wikipedia.org/wiki/floating%20point

Page 128: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

12.4

Mod

ulo

The

mod

ulus

(rem

aind

erof

the

divi

sion

ofth

etw

oop

eran

ds,r

athe

rtha

nth

equ

otie

nt)c

anbe

foun

dus

ing

the

%op

erat

or,o

rby

the

divm

odbu

iltin

func

tion.

The

divm

odfu

nctio

nre

turn

sa

tupl

eco

ntai

ning

the

quot

ient

and

rem

aind

er.

>>>

10%7

3 12.5

Neg

atio

n

Unl

ike

som

eot

herl

angu

ages

,var

iabl

esca

nbe

nega

ted

dire

ctly

:

>>>

x=

5>>>

-x

-5

Page 129: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

12.6

Aug

men

ted

Ass

ignm

ent

Ther

eis

shor

than

dfo

rass

igni

ngth

eou

tput

ofan

oper

atio

nto

one

ofth

ein

puts

:

>>>

x=

2>>>

x#

22 >>>

x*=

3>>>

x#

2*3

6 >>>

x+=

4>>>

x#

2*3

+4

10>>>

x/=

5>>>

x#

(2*3

+4)

/5

2 >>>

x**=

2>>>

x#

((2*3

+4)

/5)

**2

4 >>>

x%=

3>>>

x#

((2*3

+4)

/5)

**2

%3

1

Page 130: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

x=

'repeat

this

'>>>

x#

repeat

this

repeat

this

>>>

x*=

3#

fill

with

xrepeated

three

times

>>>

xrepeat

this

repeat

this

repeat

this

12.7

Boo

lean

or:

if

aor

b:

do_this

else: do_this

and:

if

aand

b:

Page 131: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

do_this

else: do_this

not:

if

not

a:

do_this

else: do_this

12.8

Ref

eren

ces

Page 132: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

13Fl

owco

ntro

l

As

with

mos

tim

pera

tive

lang

uage

s,th

ere

are

thre

em

ain

cate

gorie

sof

prog

ram

flow

cont

rol:

•lo

ops

•br

anch

es•

func

tion

calls

Func

tion

calls

are

cove

red

inth

ene

xtse

ctio

n1 .

1C

hapt

er14

onpa

ge13

9

125

Page 133: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Gen

erat

ors

and

list

com

preh

ensi

ons

are

adva

nced

form

sof

prog

ram

flow

cont

rol,

butt

hey

are

notc

over

edhe

re.

13.0

.1L

oops

InPy

thon

,the

rear

etw

oki

nds

oflo

ops,

'for'

loop

san

d'w

hile

'loo

ps.

For

loop

s

Afo

rlo

opite

rate

sov

erel

emen

tsof

ase

quen

ce(t

uple

orlis

t).

Ava

riab

leis

crea

ted

tore

pres

entt

heob

ject

inth

ese

quen

ce.F

orex

ampl

e,

l=

[100,200,300,400]

for

iin

l:

printi

Page 134: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illou

tput

100

200

300

400

Thefor

loop

loop

sov

erea

chof

the

elem

ents

ofa

listo

rite

rato

r,as

sign

ing

the

curr

ente

lem

entt

oth

eva

riabl

ena

me

give

n.In

the

first

exam

ple

abov

e,ea

chof

the

elem

ents

inl

isas

sign

edtoi

.

Abu

iltin

func

tion

calle

dra

nge

exis

tsto

mak

ecr

eatin

gse

quen

tiall

ists

such

asth

eon

eab

ove

easi

er.T

helo

opab

ove

iseq

uiva

lent

to:

l=

range(100,

401,100)

for

iin

l:

printi

Page 135: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

next

exam

ple

uses

ane

gativ

est

ep(th

eth

irdar

gum

entf

orth

ebu

ilt-in

rang

efu

nctio

n):

for

iin

range(10,

0,

-1):

printi

Thi

sw

illou

tput

10

9 8 7 6 5 4 3 2 1

or

Page 136: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

for

iin

range(10,

0,

-2):

printi

Thi

sw

illou

tput

10

8 6 4 2

forl

oops

can

have

nam

esfo

reac

hel

emen

tofa

tupl

e,if

itlo

opso

vera

sequ

ence

oftu

ples

.For

inst

ance

l=

[(1,

1),

(2,

4),

(3,

9),

(4,

16),

(5,

25)]

for

x,

xsquared

in

l:

printx,

':',

xsquared

Page 137: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

will

outp

ut

1:

12

:4

3:

94

:16

5:

25

Whi

lelo

ops

Aw

hile

loop

repe

ats

ase

quen

ceof

stat

emen

tsun

tilso

me

cond

ition

beco

mes

fals

e.Fo

rexa

mpl

e:

x=

5while

x>

0:

printx

x=

x-

1

Page 138: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Will

outp

ut:

5 4 3 2 1

Pyth

on's

whi

lelo

ops

can

also

have

an'e

lse'

clau

se,w

hich

isa

bloc

kof

stat

e-m

ents

that

isex

ecut

ed(o

nce)

whe

nth

ew

hile

stat

emen

teva

luat

esto

fals

e.Th

ebr

eak

stat

emen

tins

ide

the

whi

lelo

opw

illno

tdir

ectt

hepr

ogra

mflo

wto

the

else

clau

se.F

orex

ampl

e:

x=

5y

=x

while

y>

0:

printy

y=

y-

1else: printx

Page 139: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illou

tput

:

5 4 3 2 1 5

Unl

ike

som

ela

ngua

ges,

ther

eis

nopo

st-c

ondi

tion

loop

.

Bre

akin

g,co

ntin

uing

and

the

else

clau

seof

loop

s

Pyth

onin

clud

esst

atem

ents

toex

ita

loop

(eith

era

for

loop

ora

whi

lelo

op)

prem

atur

ely.

Toex

ita

loop

,use

the

brea

kst

atem

ent

x=

5while

x>

0:

printx

Page 140: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

break

x-=

1printx

this

will

outp

ut

5

The

stat

emen

tto

begi

nth

ene

xtite

ratio

nof

the

loop

with

outw

aitin

gfo

rthe

end

ofth

ecu

rren

tloo

pis

'con

tinue

'.

l=

[5,6,7]

for

xin

l:

continue

printx

Thi

sw

illno

tpro

duce

any

outp

ut.

The

else

clau

seof

loop

sw

illbe

exec

uted

ifno

brea

kst

atem

ents

are

met

inth

elo

op.

Page 141: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

l=

range(1,100)

for

xin

l:

ifx

==

100:

printx

break

else: printx,"

is

not

100"

else: print"100

not

found

in

range"

Ano

ther

exam

ple

ofa

whi

lelo

opus

ing

the

brea

kst

atem

ent

and

the

else

stat

emen

t:

expected_str

="melon"

received_str

="apple"

basket

=["banana",

"grapes",

"strawberry",

"melon",

"orange"]

x=

0step

=int(raw_input("Input

iteration

step:

"))

while(received_str

!=

expected_str):

if(x

>=

len(basket)):

print

"No

more

fruits

left

on

the

basket.";

break

Page 142: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

received_str

=basket[x]

x+=

step#

Change

this

to

3to

make

the

while

statement

#evaluate

to

false,

avoiding

the

break

statement,

using

the

else

clause.

if(received_str==basket[2]):

print"I

hate",basket[2],"!";

break

if(received_str

!=

expected_str):print

"I

am

waiting

for

my

",expected_str,"."

else: print"Finally

got

what

Iwanted!

my

precious

",expected_str,"!"

print

"Going

back

home

now

!"

Thi

sw

illou

tput

:

Input

iteration

step:

2I

am

waiting

for

my

melon

.I

hate

strawberry

!Going

back

home

now

!

Page 143: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

13.0

.2B

ranc

hes

The

reis

basi

cally

only

one

kind

ofbr

anch

inPy

thon

,the

'if's

tate

men

t.T

hesi

mpl

estf

orm

ofth

eif

stat

emen

tsim

ple

exec

utes

abl

ock

ofco

deon

lyif

agi

ven

pred

icat

eis

true

,and

skip

sov

erit

ifth

epr

edic

ate

isfa

lse

Fori

nsta

nce,

>>>

x=

10

>>>

ifx

>0:

...

print"Positive"

...

Positive

>>>

ifx

<0:

...

print"Negative"

...

You

can

also

add

"elif

"(s

hort

for"

else

if")

bran

ches

onto

the

ifst

atem

ent.

Ifth

epr

edic

ate

onth

efir

st“i

f”is

fals

e,it

will

test

the

pred

icat

eon

the

first

elif

,an

dru

nth

atbr

anch

ifit’

str

ue.I

fthe

first

elif

isfa

lse,

ittr

ies

the

seco

ndon

e,an

dso

on.N

ote,

how

ever

,tha

titw

illst

opch

ecki

ngbr

anch

esas

soon

asit

finds

Page 144: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

atr

uepr

edic

ate,

and

skip

the

rest

ofth

eif

stat

emen

t.Y

ouca

nal

soen

dyo

urif

stat

emen

tsw

ithan

"els

e"br

anch

.Ifn

one

ofth

eot

herb

ranc

hes

are

exec

uted

,th

enpy

thon

will

run

this

bran

ch.

>>>

x=

-6

>>>

ifx

>0:

...

print"Positive"

...

elifx

==

0:

...

print"Zero"

...

else:

...

print"Negative"

...

'Negative'

13.0

.3C

oncl

usio

n

Any

ofth

ese

loop

s,br

anch

es,a

ndfu

nctio

nca

llsca

nbe

nest

edin

any

way

desi

red.

Alo

opca

nlo

opov

era

loop

,abr

anch

can

bran

chag

ain,

and

afu

nctio

nca

nca

llot

herf

unct

ions

,ore

ven

call

itsel

f.

Page 145: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 146: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

14Fu

nctio

ns

14.0

.4Fu

nctio

nca

lls

Aca

llabl

eob

ject

isan

obje

ctth

atca

nac

cept

som

ear

gum

ents

(als

oca

lled

para

met

ers)

and

poss

ibly

retu

rnan

obje

ct(o

ften

atu

ple

cont

aini

ngm

ultip

leob

ject

s).

Afu

nctio

nis

the

sim

ples

tcal

labl

eob

ject

inPy

thon

,but

ther

ear

eot

hers

,suc

has

clas

ses1

orce

rtai

ncl

ass

inst

ance

s.

1C

hapt

er19

onpa

ge18

9

139

Page 147: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Defi

ning

func

tions

Afu

nctio

nis

defin

edin

Pyth

onby

the

follo

win

gfo

rmat

:

def

functionname(arg1,

arg2,

...):

statement1

statement2

...

>>>

deffunctionname(arg1,arg2):

...

returnarg1+arg2

...

>>>

t=

functionname(24,24)

#Result:

48

Ifa

func

tion

take

sno

argu

men

ts,

itm

ust

still

incl

ude

the

pare

nthe

ses,

but

with

outa

nyth

ing

inth

em:

def

functionname():

statement1

statement2

...

Page 148: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

argu

men

tsin

the

func

tion

defin

ition

bind

the

argu

men

tspa

ssed

atfu

nctio

nin

voca

tion

(i.e.

whe

nth

efu

nctio

nis

calle

d),w

hich

are

calle

dac

tual

para

met

ers,

toth

ena

mes

give

nw

hen

the

func

tion

isde

fined

,w

hich

are

calle

dfo

rmal

para

met

ers.

The

inte

rior

ofth

efu

nctio

nha

sno

know

ledg

eof

the

nam

esgi

ven

toth

eac

tual

para

met

ers;

the

nam

esof

the

actu

alpa

ram

eter

sm

ayno

teve

nbe

acce

ssib

le(t

hey

coul

dbe

insi

dean

othe

rfun

ctio

n).

Afu

nctio

nca

n're

turn

'ava

lue,

fore

xam

ple:

def

square(x):

returnx*x

Afu

nctio

nca

nde

fine

varia

bles

with

inth

efu

nctio

nbo

dy,w

hich

are

cons

ider

ed'lo

cal'

toth

efu

nctio

n.T

helo

cals

toge

ther

with

the

argu

men

tsco

mpr

ise

allt

heva

riab

les

with

inth

esc

ope

ofth

efu

nctio

n.A

nyna

mes

with

inth

efu

nctio

nar

eun

boun

dw

hen

the

func

tion

retu

rns

orre

ache

sth

een

dof

the

func

tion

body

.

Page 149: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Dec

lari

ngA

rgum

ents

Def

ault

Arg

umen

tVal

ues

Ifan

yof

the

form

alpa

ram

eter

sin

the

func

tion

defin

ition

are

decl

ared

with

the

form

at"a

rg=

valu

e,"

then

you

will

have

the

optio

nof

nots

peci

fyin

ga

valu

efo

rtho

sear

gum

ents

whe

nca

lling

the

func

tion.

Ifyo

udo

nots

peci

fya

valu

e,th

enth

atpa

ram

eter

will

have

the

defa

ultv

alue

give

nw

hen

the

func

tion

exec

utes

.

>>>

defdisplay_message(message,

truncate_after=4):

...

printmessage[:truncate_after]

...

>>>

display_message("message")

mess

>>>

display_message("message",

6)

messag

Page 150: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Vari

able

-Len

gth

Arg

umen

tLis

ts

Pyth

onal

low

syo

uto

decl

are

two

spec

iala

rgum

ents

whi

chal

low

you

tocr

eate

arbi

trary

-leng

thar

gum

entl

ists

.Thi

smea

nsth

atea

chtim

eyo

uca

llth

efu

nctio

n,yo

uca

nsp

ecif

yan

ynu

mbe

rofa

rgum

ents

abov

ea

cert

ain

num

ber.

def

function(first,second,*remaining):

statement1

statement2

...

Whe

nca

lling

the

abov

efu

nctio

n,yo

um

ustp

rovi

deva

lue

fore

ach

ofth

efir

sttw

oar

gum

ents

.How

ever

,sin

ceth

eth

irdpa

ram

eter

ism

arke

dw

ithan

aste

risk,

any

actu

alpa

ram

eter

saf

tert

hefir

sttw

ow

illbe

pack

edin

toa

tupl

ean

dbo

und

to"r

emai

ning

."

>>>

defprint_tail(first,*tail):

...

printtail

...

Page 151: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

print_tail(1,

5,

2,

"omega")

(5,

2,

'omega')

Ifw

ede

clar

ea

form

alpa

ram

eter

prefi

xed

with

two

aste

risk

s,th

enit

will

bebo

und

toa

dict

iona

ryco

ntai

ning

any

keyw

ord

argu

men

tsin

the

actu

alpa

ram

eter

sw

hich

dono

tcor

resp

ond

toan

yfo

rmal

para

met

ers.

Fore

xam

ple,

cons

ider

the

func

tion:

def

make_dictionary(max_length=10,**entries):

returndict([(key,

entries[key])

fori,

key

in

enumerate(entries.keys())if

i<

max_length])

Ifw

eca

llth

isfu

nctio

nw

ithan

yke

ywor

dar

gum

ents

othe

rtha

nm

ax_l

engt

h,th

eyw

illbe

plac

edin

the

dict

iona

ry"e

ntri

es."

Ifw

ein

clud

eth

eke

ywor

dar

gum

ento

fmax

_len

gth,

itw

illbe

boun

dto

the

form

alpa

ram

eter

max

_len

gth,

asus

ual.

>>>

make_dictionary(max_length=2,

key1=5,

key2=7,

key3=9)

{'key3':

9,

'key2':

7}

Page 152: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Cal

ling

func

tions

Afu

nctio

nca

nbe

calle

dby

appe

ndin

gth

ear

gum

ents

inpa

rent

hese

sto

the

func

tion

nam

e,or

anem

pty

mat

ched

seto

fpar

enth

eses

ifth

efu

nctio

nta

kes

noar

gum

ents

.

foo()

square(3)

bar(5,

x)

Afu

nctio

n's

retu

rnva

lue

can

beus

edby

assi

gnin

git

toa

vari

able

,lik

eso

:

x=

foo()

y=

bar(5,x)

As

show

nab

ove,

whe

nca

lling

afu

nctio

nyo

uca

nsp

ecif

yth

epa

ram

eter

sby

nam

ean

dyo

uca

ndo

soin

any

orde

r

def

display_message(message,

start=0,

end=4):

Page 153: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

printmessage[start:end]

display_message("message",

end=3)

This

abov

eis

valid

and

star

twill

beth

ede

faul

tval

ueof

0.A

rest

rictio

npl

aced

onth

isis

afte

rthe

first

nam

edar

gum

entt

hen

alla

rgum

ents

afte

ritm

usta

lso

bena

med

.The

follo

win

gis

notv

alid

display_message(end=5,

start=1,

"my

message")

beca

use

the

thir

dar

gum

ent(

"my

mes

sage

")is

anun

nam

edar

gum

ent.

14.0

.5C

losu

re

Acl

osur

e,al

sokn

own

asne

sted

func

tion

defin

ition

,is

afu

nctio

nde

fined

insi

dean

othe

rfun

ctio

n.Pe

rhap

sbe

stde

scri

bed

with

anex

ampl

e:

>>>

defouter(outer_argument):

Page 154: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

...

definner(inner_argument):

...

return

outer_argument

+inner_argument

...

returninner

...

>>>

f=

outer(5)

>>>

f(3)

8 >>>

f(4)

9 Clo

sure

sar

epo

ssib

lein

Pyth

onbe

caus

efu

nctio

nsar

efir

st-c

lass

obje

cts.

Afu

nctio

nis

mer

ely

anob

ject

ofty

pefu

nctio

n.B

eing

anob

ject

mea

nsit

ispo

ssib

leto

pass

afu

nctio

nob

ject

(an

unca

lled

func

tion)

arou

ndas

argu

men

tor

asre

turn

valu

eor

toas

sign

anot

hern

ame

toth

efu

nctio

nob

ject

.Aun

ique

feat

ure

that

mak

escl

osur

eus

eful

isth

atth

een

clos

edfu

nctio

nm

ayus

eth

ena

mes

defin

edin

the

pare

ntfu

nctio

n's

scop

e.

Page 155: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

lam

bda

lam

bda

isan

anon

ymou

s(u

nnam

ed)f

unct

ion.

Itis

used

prim

arily

tow

rite

very

shor

tfun

ctio

nsth

atar

ea

hass

leto

defin

ein

the

norm

alw

ay.A

func

tion

like

this

:

>>>

defadd(a,

b):

...

returna

+b

...

>>>

add(4,

3)

7 may

also

bede

fined

usin

gla

mbd

a

>>>

print(lambda

a,

b:

a+

b)(4,

3)

7 Lam

bda

isof

ten

used

asan

argu

men

tto

othe

rfun

ctio

nsth

atex

pect

sa

func

tion

obje

ct,s

uch

asso

rted

()'s

'key

'arg

umen

t.

Page 156: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

sorted([[3,

4],

[3,

5],

[1,

2],

[7,

3]],

key=lambdax:

x[1])

[[1,

2],

[7,

3],

[3,

4],

[3,

5]]

The

lam

bda

form

isof

ten

usef

ulas

acl

osur

e,su

chas

illus

trate

din

the

follo

win

gex

ampl

e:

>>>

defattribution(name):

...

return

lambda

x:

x+

'--

'+

name

...

>>>

pp

=attribution('John')

>>>

pp('Dinner

is

in

the

fridge')

'Dinner

is

in

the

fridge

--

John'

note

that

the

lam

bda

func

tion

can

use

the

valu

esof

vari

able

sfr

omth

esc

ope2

inw

hich

itw

ascr

eate

d(l

ike

pre

and

post

).T

his

isth

ees

senc

eof

clos

ure.

2C

hapt

er15

onpa

ge15

1

Page 157: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

de:P

ytho

n-Pr

ogra

mm

ieru

ng:_

Funk

tione

n3es

:Inm

ersi

ónen

Pyth

on/S

upr

imer

prog

ram

aen

Pyth

on/D

ecla

raci

ónde

func

ione

s4fr

:Pro

gram

mat

ion_

-Py

thon

/Fon

ctio

n5pt

:Pyt

hon/

Con

ceito

sbá

sico

s/Fu

nçõe

s6

3http://de.wikibooks.org/wiki/Python-Programmierung%3A_

Funktionen

4http://es.wikibooks.org/wiki/Inmersi%F3n%20en%20Python%

2FSu%20primer%20programa%20en%20Python%2FDeclaraci%F3n%

20de%20funciones

5http://fr.wikibooks.org/wiki/Programmation_Python%

2FFonction

6http://pt.wikibooks.org/wiki/Python%2FConceitos%20b%

E1sicos%2FFun%E7%F5es

Page 158: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

15Sc

opin

g

15.0

.6Va

riab

les

Var

iabl

esin

Pyth

onar

eau

tom

atic

ally

decl

ared

byas

sign

men

t.V

aria

bles

are

alw

ays

refe

renc

esto

obje

cts,

and

are

neve

rtyp

ed.V

aria

bles

exis

tonl

yin

the

curr

ents

cope

orgl

obal

scop

e.W

hen

they

goou

tof

scop

e,th

eva

riab

les

are

dest

roye

d,bu

tthe

obje

cts

tow

hich

they

refe

rar

eno

t(un

less

the

num

ber

ofre

fere

nces

toth

eob

ject

drop

sto

zero

).

Scop

eis

delin

eate

dby

func

tion

and

clas

sbl

ocks

.B

oth

func

tions

and

thei

rsc

opes

can

bene

sted

.So

ther

efor

e

151

Page 159: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

def

foo():

defbar():

x=

5#

xis

now

in

scope

returnx

+y

#y

is

defined

in

the

enclosing

scope

later

y=

10

returnbar()

#now

that

yis

defined,

bar's

scope

includes

y

Now

whe

nth

isco

deis

test

ed,

>>>

foo()

15

>>>

bar()

Traceback

(most

recent

call

last):

File

"<pyshell#26>",

line

1,

in

-toplevel-

bar()

NameError:

name

'bar'

is

not

defined

The

nam

e'b

ar'i

sno

tfou

ndbe

caus

ea

high

ersc

ope

does

noth

ave

acce

ssto

the

nam

eslo

wer

inth

ehi

erar

chy.

Page 160: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Itis

aco

mm

onpi

tfal

lto

fail

tolo

okup

anat

trib

ute

(suc

has

am

etho

d)of

anob

ject

(suc

has

aco

ntai

ner)

refe

renc

edby

ava

riab

lebe

fore

the

vari

able

isas

sign

edth

eob

ject

.In

itsm

ostc

omm

onfo

rm:

>>>

forx

in

range(10):

y.append(x)

#append

is

an

attribute

of

lists

Traceback

(most

recent

call

last):

File

"<pyshell#46>",

line

2,

in

-toplevel-

y.append(x)

NameError:

name

'y'

is

not

defined

Her

e,to

corr

ectt

his

prob

lem

,one

mus

tadd

y=

[]be

fore

the

forl

oop.

Page 161: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 162: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

16E

xcep

tions

Pyth

onha

ndle

sal

lerr

ors

with

exce

ptio

ns.

An

exce

ptio

nis

asi

gnal

that

aner

roro

roth

erun

usua

lcon

ditio

nha

soc

curr

ed.

The

rear

ea

num

ber

ofbu

ilt-i

nex

cept

ions

,w

hich

indi

cate

cond

ition

slik

ere

adin

gpa

stth

een

dof

afil

e,or

divi

ding

byze

ro.

You

can

also

defin

eyo

urow

nex

cept

ions

.

155

Page 163: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

16.0

.7R

aisi

ngex

cept

ions

Whe

neve

ryou

rpro

gram

atte

mpt

sto

doso

met

hing

erro

neou

sor

mea

ning

less

,Py

thon

rais

esex

cept

ion

tosu

chco

nduc

t:

>>>

1/

0Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?ZeroDivisionError:

integer

division

or

modulo

by

zero

Thi

str

aceb

ack

indi

cate

sth

atth

eZ

eroD

ivis

ionE

rror

exce

ptio

nis

bein

gra

ised

.T

his

isa

built

-in

exce

ptio

n--

see

belo

wfo

ralis

tofa

llth

eot

hero

nes.

16.0

.8C

atch

ing

exce

ptio

ns

Inor

der

toha

ndle

erro

rs,y

ouca

nse

tup

exce

ptio

nha

ndlin

gbl

ocks

inyo

urco

de.

The

keyw

ords

try

and

exce

ptar

eus

edto

catc

hex

cept

ions

.W

hen

an

Page 164: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

erro

rocc

urs

with

inth

etr

ybl

ock,

Pyth

onlo

oks

fora

mat

chin

gex

cept

bloc

kto

hand

leit.

Ifth

ere

ison

e,ex

ecut

ion

jum

psth

ere.

Ifyo

uex

ecut

eth

isco

de:

try:print1/0

except

ZeroDivisionError:

print"You

can't

divide

by

zero,

you're

silly."

The

nPy

thon

will

prin

tthi

s:

You

can't

divide

by

zero,

you're

silly.

Ifyo

udo

n'ts

peci

fyan

exce

ptio

nty

peon

the

exce

ptlin

e,it

will

chee

rful

lyca

tch

alle

xcep

tions

.Thi

sis

gene

rally

aba

did

eain

prod

uctio

nco

de,s

ince

itm

eans

your

prog

ram

will

blis

sful

lyig

nore

unex

pect

eder

rors

asw

ella

son

esw

hich

the

exce

ptbl

ock

isac

tual

lypr

epar

edto

hand

le.

Page 165: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Exc

eptio

nsca

npr

opag

ate

upth

eca

llst

ack:

def

f(x):

returng(x)

+1

def

g(x):

ifx

<0:raise

ValueError,

"I

can't

cope

with

anegative

number

here."else:return

5

try:printf(-6)

except

ValueError:

print"That

value

was

invalid."

Inth

isco

de,

the

prin

tst

atem

ent

calls

the

func

tion

f.T

hat

func

tion

calls

the

func

tion

g,w

hich

will

rais

ean

exce

ptio

nof

type

Val

ueE

rror

.N

eith

erf

nor

gha

sa

try/

exce

ptbl

ock

toha

ndle

Val

ueE

rror

.So

the

exce

ptio

nra

ised

prop

agat

esou

tto

the

mai

nco

de,w

here

ther

eis

anex

cept

ion-

hand

ling

bloc

kw

aitin

gfo

rit.

Thi

sco

depr

ints

:

Page 166: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

That

value

was

invalid.

Som

etim

esit

isus

eful

tofin

dou

texa

ctly

wha

twen

twro

ng,o

rto

prin

tthe

pyth

oner

rort

exty

ours

elf.

Fore

xam

ple:

try: the_file

=open("the_parrot")

exceptIOError,

(ErrorNumber,

ErrorMessage):

ifErrorNumber

==

2:#

file

not

found

print"Sorry,

'the_parrot'

has

apparently

joined

the

choir

invisible."

else:print"Congratulation!

you

have

managed

to

trip

a#%d

error"

%ErrorNumber

printErrorMessage

Whi

chof

cour

sew

illpr

int:

Page 167: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Sorry,

'the_parrot'

has

apparently

joined

the

choir

invisible.

Cus

tom

Exc

eptio

ns

Cod

esi

mila

rto

that

seen

abov

eca

nbe

used

tocr

eate

cust

omex

cept

ions

and

pass

info

rmat

ion

alon

gw

ithth

em.T

his

can

beex

trem

ely

usef

ulw

hen

tryi

ngto

debu

gco

mpl

icat

edpr

ojec

ts.H

ere

isho

wth

atco

dew

ould

look

;firs

tcre

atin

gth

ecu

stom

exce

ptio

ncl

ass:

classCustomException(Exception):

def__init__(self,

value):

self.parameter

=value

def__str__(self):

return

repr(self.parameter)

And

then

usin

gth

atex

cept

ion:

Page 168: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

try:raiseCustomException("My

Useful

Error

Message")

except

CustomException,

(instance):

print"Caught:

"+

instance.parameter

Tryi

ngov

eran

dov

erag

ain

16.0

.9R

ecov

erin

gan

dco

ntin

uing

with

final

ly

Exce

ptio

nsco

uld

lead

toa

situ

atio

nw

here

,afte

rrai

sing

anex

cept

ion,

the

code

bloc

kw

here

the

exce

ptio

noc

curr

edm

ight

notb

ere

visi

ted.

Inso

me

case

sth

ism

ight

leav

eex

tern

alre

sour

ces

used

byth

epr

ogra

min

anun

know

nst

ate.

finally

clau

seal

low

spr

ogra

mm

ers

tocl

ose

such

reso

urce

sin

case

ofan

exce

ptio

n.B

etw

een

2.4

and

2.5

vers

ion

ofpy

thon

ther

eis

chan

geof

synt

axfo

rfinally

clau

se.

•Py

thon

2.4

Page 169: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

try:result

=None

try: result

=x/y

exceptZeroDivisionError:

print"division

by

zero!"

print"result

is

",

result

finally:

print"executing

finally

clause"

•Py

thon

2.5

try:result

=x

/y

except

ZeroDivisionError:

print"division

by

zero!"

else:print"result

is",

result

finally:

print"executing

finally

clause"

Page 170: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

16.0

.10

Bui

lt-in

exce

ptio

ncl

asse

s

All

built

-in

Pyth

onex

cept

ions

1

16.0

.11

Exo

ticus

esof

exce

ptio

ns

Exc

eptio

nsar

ego

odfo

rmor

eth

anju

ster

rorh

andl

ing.

Ifyo

uha

vea

com

pli-

cate

dpi

ece

ofco

deto

choo

sew

hich

ofse

vera

lcou

rses

ofac

tion

tota

ke,i

tcan

beus

eful

tous

eex

cept

ions

toju

mp

outo

fth

eco

deas

soon

asth

ede

cisi

onca

nbe

mad

e.T

hePy

thon

-bas

edm

ailin

glis

tsof

twar

eM

ailm

ando

esth

isin

deci

ding

how

am

essa

gesh

ould

beha

ndle

d.U

sing

exce

ptio

nslik

eth

ism

ayse

emlik

eit'

sa

sort

ofG

OT

O--

and

inde

edit

is,b

uta

limite

don

eca

lled

anes

cape

cont

inua

tion.

Con

tinua

tions

are

apo

wer

fulf

unct

iona

l-pr

ogra

mm

ing

tool

and

itca

nbe

usef

ulto

lear

nth

em.

1http://docs.python.org/library/exceptions.html

Page 171: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Just

asa

sim

ple

exam

ple

ofho

wex

cept

ions

mak

epr

ogra

mm

ing

easi

er,s

ayyo

uw

antt

oad

dite

ms

toa

listb

utyo

udo

n'tw

antt

ous

e"i

f"st

atem

ents

toin

itial

ize

the

listw

eco

uld

repl

ace

this

:

if

hasattr(self,

'items'):

self.items.extend(new_items)

else: self.items

=list(new_items)

Usi

ngex

cept

ions

,we

can

emph

asiz

eth

eno

rmal

prog

ram

flow

—th

atus

ually

we

just

exte

ndth

elis

t—ra

ther

than

emph

asiz

ing

the

unus

ualc

ase:

try:self.items.extend(new_items)

except

AttributeError:

self.items

=list(new_items)

Page 172: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

17In

puta

ndou

tput

17.1

Inpu

t

Pyth

onha

stw

ofu

nctio

nsde

sign

edfo

racc

eptin

gda

tadi

rect

lyfr

omth

eus

er:

•input()

•raw_input()

The

rear

eal

sove

rysi

mpl

ew

ays

ofre

adin

ga

file

and,

fors

tric

terc

ontr

olov

erin

put,

read

ing

from

stdi

nif

nece

ssar

y.

165

Page 173: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

17.1

.1ra

w_i

nput

()

raw

_inp

ut()

asks

the

user

for

ast

ring

ofda

ta(e

nded

with

ane

wlin

e),

and

sim

ply

retu

rns

the

strin

g.It

can

also

take

anar

gum

ent,

whi

chis

disp

laye

das

apr

ompt

befo

reth

eus

eren

ters

the

data

.E.g

.

print

raw_input('What

is

your

name?

')

prin

tsou

t

What

is

your

name?

<user

input

data

here>

Exa

mpl

e:in

orde

rto

assi

gnth

eus

er's

nam

e,i.e

.str

ing

data

,to

ava

riab

le"x

"yo

uw

ould

type

x=

raw_input('What

is

your

name?')

Onc

eth

eus

erin

puts

his

nam

e,e.

g.Si

mon

,you

can

call

itas

x

Page 174: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

print

('Your

name

is

'+

x)

prin

tsou

t

Your

name

is

Simon

Not

e:in

3.x

"...r

aw_i

nput

()w

asre

nam

edto

inpu

t().

Tha

tis

,th

ene

win

put(

)fu

nctio

nre

ads

alin

efr

omsy

s.st

din

and

retu

rns

itw

ithth

etr

ailin

gne

wlin

est

ripp

ed.I

trai

ses

EO

FErr

orif

the

inpu

tis

term

inat

edpr

emat

urel

y.To

get

the

old

beha

vior

ofin

put(

),us

eev

al(i

nput

())."

Page 175: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

17.1

.2in

put(

)

inpu

t()u

ses

raw

_inp

utto

read

ast

ring

ofda

ta,a

ndth

enat

tem

pts

toev

alua

teit

asif

itw

ere

aPy

thon

prog

ram

,and

then

retu

rns

the

valu

eth

atre

sults

.So

ente

ring

[1,2,3]

wou

ldre

turn

alis

tcon

tain

ing

thos

enu

mbe

rs,j

usta

sif

itw

ere

assi

gned

dire

ctly

inth

ePy

thon

scri

pt.

Mor

eco

mpl

icat

edex

pres

sion

sar

epo

ssib

le.F

orex

ampl

e,if

asc

ript

says

:

x=

input('What

are

the

first

10

perfect

squares?

')

itis

poss

ible

fora

user

toin

put:

map(lambdax:

x*x,

range(10))

Page 176: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

whi

chyi

elds

the

corr

ecta

nsw

erin

listf

orm

.Not

eth

atno

inpu

tted

stat

emen

tca

nsp

anm

ore

than

one

line.

inpu

t()s

houl

dno

tbe

used

fora

nyth

ing

butt

hem

ostt

rivia

lpro

gram

.Tur

ning

the

stri

ngs

retu

rned

from

raw

_inp

ut()

into

pyth

onty

pes

usin

gan

idio

msu

chas

:

x=

None

while

not

x:

try:x

=int(raw_input())

exceptValueError:

print'Invalid

Number'

ispr

efer

able

,as

inpu

t()

uses

eval

()to

turn

alit

eral

into

apy

thon

type

.T

his

will

allo

wa

mal

icio

uspe

rson

toru

nar

bitr

ary

code

from

insi

deyo

urpr

ogra

mtr

ivia

lly.

Page 177: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

17.1

.3Fi

leIn

put

File

Obj

ects

Pyth

onin

clud

esa

built

-infil

ety

pe.F

iles

can

beop

ened

byus

ing

the

file

type

'sco

nstr

ucto

r:

f=

file('test.txt',

'r')

Thi

sm

eans

fis

open

forr

eadi

ng.T

hefir

star

gum

enti

sth

efil

enam

ean

dth

ese

cond

para

met

eris

the

mod

e,w

hich

can

be'r'

,'w

',or

'rw',

amon

gso

me

othe

rs.

The

mos

tcom

mon

way

tore

adfr

oma

file

issi

mpl

yto

itera

teov

erth

elin

esof

the

file:

f=

open('test.txt',

'r')

for

line

in

f:

printline[0]

f.close()

Page 178: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illpr

intt

hefir

stch

arac

tero

feac

hlin

e.N

ote

that

ane

wlin

eis

atta

ched

toth

een

dof

each

line

read

this

way

.

Bec

ause

files

are

auto

mat

ical

lycl

osed

whe

nth

efil

eob

ject

goes

outo

fsco

pe,

ther

eis

nore

alne

edto

clos

eth

emex

plic

itly.

So,t

helo

opin

the

prev

ious

code

can

also

bew

ritte

nas

:

for

line

in

open('test.txt',

'r'):

printline[0]

Itis

also

poss

ible

tore

adlim

ited

num

bers

ofch

arac

ters

ata

time,

like

so:

c=

f.read(1)

while

len(c)

>0:

iflen(c.strip())

>0:print

c,

c=

f.read(1)

This

will

read

the

char

acte

rsfr

omfo

neat

atim

e,an

dth

enpr

intt

hem

ifth

ey're

notw

hite

spac

e.

Page 179: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Afil

eob

ject

impl

icitl

yco

ntai

nsa

mar

kert

ore

pres

entt

hecu

rren

tpos

ition

.If

the

file

mar

kers

houl

dbe

mov

edba

ckto

the

begi

nnin

g,on

eca

nei

ther

clos

eth

efil

eob

ject

and

reop

enit

orju

stm

ove

the

mar

kerb

ack

toth

ebe

ginn

ing

with

:

f.seek(0)

Stan

dard

File

Obj

ects

Like

man

yot

herl

angu

ages

,the

rear

ebu

ilt-in

file

obje

cts

repr

esen

ting

stan

dard

inpu

t,ou

tput

,an

der

ror.

The

sear

ein

the

sys

mod

ule

and

are

calle

dst

din,

stdo

ut,

and

stde

rr.

The

rear

eal

soim

mut

able

copi

esof

thes

ein

__st

din_

_,__

stdo

ut__

,and

__st

derr

__.

Thi

sis

for

IDL

Ean

dot

her

tool

sin

whi

chth

est

anda

rdfil

esha

vebe

ench

ange

d.

You

mus

tim

port

the

sys

mod

ule

tous

eth

esp

ecia

lstd

in,s

tdou

t,st

derr

I/O

hand

les.

Page 180: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

import

sys

For

finer

cont

rolo

ver

inpu

t,us

esy

s.st

din.

read

().

Inor

der

toim

plem

entt

heU

NIX

'cat

'pro

gram

inPy

thon

,you

coul

ddo

som

ethi

nglik

eth

is:

import

sys

for

line

in

sys.stdin:

printline,

Not

eth

atsy

s.st

din.

read

()w

illre

adfr

omst

anda

rdin

putt

illE

OF.

(whi

chis

usua

llyC

trl+

D.)

Als

oim

port

ant

isth

esy

s.ar

gvar

ray.

sys.

argv

isan

arra

yth

atco

ntai

nsth

eco

mm

and-

line

argu

men

tspa

ssed

toth

epr

ogra

m.

python

program.py

hello

there

programmer!

Page 181: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sar

ray

can

bein

dexe

d,an

dth

ear

gum

ents

eval

uate

d.In

the

abov

eex

ampl

e,sy

s.ar

gv[2

]wou

ldco

ntai

nth

est

ring

"the

re",

beca

use

the

nam

eof

the

prog

ram

("pr

ogra

m.p

y")

isst

ored

inar

gv[0

].Fo

rm

ore

com

plic

ated

com

man

d-lin

ear

gum

entp

roce

ssin

g,se

eth

e"a

rgpa

rse"

mod

ule.

17.2

Out

put

The

basi

cw

ayto

doou

tput

isth

epr

ints

tate

men

t.

print('Hello,

world')

Thi

sco

deou

ghtt

obe

obvi

ous.

Inor

dert

opr

intm

ultip

leth

ings

onth

esa

me

line,

use

com

mas

betw

een

them

,lik

eso

:

print('Hello,',

'World')

Page 182: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illpr

into

utth

efo

llow

ing:

Hello,

World

Not

eth

atal

thou

ghne

ither

stri

ngco

ntai

ned

asp

ace,

asp

ace

was

adde

dby

the

prin

tsta

tem

entb

ecau

seof

the

com

ma

betw

een

the

two

obje

cts.

Arb

itrar

yda

taty

pes

can

bepr

inte

dth

isw

ay:

print

1,2,0xff,0777,(10+5j),-0.999,map,sys

Thi

sw

illpr

into

ut:

12

255

511

(10+5j)

-0.999

<built-in

function

map>

<module

'sys'

(built-in)>

Obj

ects

can

bepr

inte

don

the

sam

elin

ew

ithou

tnee

ding

tobe

onth

esa

me

line

ifon

epu

tsa

com

ma

atth

een

dof

apr

ints

tate

men

t:

Page 183: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

for

iin

range(10):

printi,

will

outp

ut:

01

23

45

67

89

Inor

dert

oen

dth

islin

e,it

may

bene

cess

ary

toad

da

prin

tsta

tem

entw

ithou

tan

yob

ject

s.

for

iin

range(10):

printi,

print

for

iin

range(10,20):

printi,

will

outp

ut:

Page 184: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

01

23

45

67

89

10

11

12

13

14

15

16

17

18

19

Ifth

eba

repr

ints

tate

men

twer

eno

tpre

sent

,the

abov

eou

tput

wou

ldlo

oklik

e:

01

23

45

67

89

10

11

12

13

14

15

16

17

18

19

17.2

.1Pr

intin

gw

ithou

tcom

mas

orne

wlin

es

Ifit

isno

tdes

irab

leto

add

spac

esbe

twee

nob

ject

s,bu

tyou

wan

tto

run

them

allt

oget

hero

non

elin

e,th

ere

are

seve

ralt

echn

ique

sfo

rdoi

ngth

at.

conc

aten

atio

n

Con

cate

nate

the

strin

gre

pres

enta

tions

ofea

chob

ject

,the

nla

terp

rintt

hew

hole

thin

gat

once

.

Page 185: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

print

str(1

)+str(2)+str(0xff)+str(0777)+str(10+5j)+str(-0.999)+str(map)+str(sys)

will

outp

ut:

12255511(10+5j)-0.999<built-in

function

map><module

'sys'

(built-in)>

wri

te

you

can

mak

ea

shor

than

dfo

rsys

.std

out.w

rite

and

use

that

foro

utpu

t.

import

sys

write

=sys.stdout.write

write('20')

write('05\n')

will

outp

ut:

Page 186: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2005

You

may

need

sys.

stdo

ut.fl

ush(

)to

gett

hatt

exto

nth

esc

reen

quic

kly.

Itis

also

poss

ible

tous

esi

mila

rsy

ntax

whe

nw

ritin

gto

afil

e,in

stea

dof

tost

anda

rdou

tput

,lik

eso

:

print

>>

f,

'Hello,

world'

Thi

sw

illpr

int

toan

yob

ject

that

impl

emen

tsw

rite

(),

whi

chin

clud

esfil

eob

ject

s.

Page 187: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 188: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

18M

odul

es

Mod

ules

are

asi

mpl

ew

ayto

stru

ctur

ea

prog

ram

.Mos

tly,t

here

are

mod

ules

inth

est

anda

rdlib

rary

and

ther

ear

eot

herP

ytho

nfil

es,o

rdir

ecto

ries

cont

aini

ngPy

thon

files

,in

the

curr

entd

irect

ory

(eac

hof

whi

chco

nstit

ute

am

odul

e).Y

ouca

nal

soin

stru

ctPy

thon

tose

arch

othe

rdi

rect

orie

sfo

rm

odul

esby

plac

ing

thei

rpat

hsin

the

PYT

HO

NPA

TH

envi

ronm

entv

aria

ble.

18.1

Impo

rtin

ga

Mod

ule

Mod

ules

inPy

thon

are

used

byim

port

ing

them

.For

exam

ple,

181

Page 189: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

import

math

Thi

sim

port

sth

em

ath

stan

dard

mod

ule.

All

ofth

efu

nctio

nsin

that

mod

ule

are

nam

espa

ced

byth

em

odul

ena

me,

i.e.

import

math

print

math.sqrt(10)

Thi

sis

ofte

na

nuis

ance

,so

othe

rsyn

taxe

sar

eav

aila

ble

tosi

mpl

ify

this

,

from

string

import

whitespace

from

math

import

*from

math

import

sin

as

SIN

from

math

import

cos

as

COS

from

ftplib

import

FTP

as

ftp_connection

print

sqrt(10)

The

first

stat

emen

tmea

nsw

hite

spac

eis

adde

dto

the

curr

ents

cope

(but

noth

-in

gel

seis

).T

hese

cond

stat

emen

tmea

nsth

atal

lthe

elem

ents

inth

em

ath

nam

espa

ceis

adde

dto

the

curr

ents

cope

.

Page 190: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Mod

ules

can

beth

ree

diff

eren

tkin

dsof

thin

gs:

•Py

thon

files

•Sh

ared

Obj

ects

(und

erU

nix

and

Lin

ux)w

ithth

e.s

osu

ffix

•D

LL

's(u

nder

Win

dow

s)w

ithth

e.p

ydsu

ffix

•di

rect

orie

s

Mod

ules

are

load

edin

the

orde

rthe

y're

foun

d,w

hich

isco

ntro

lled

bysy

s.pa

th.

The

curr

entd

irec

tory

isal

way

son

the

path

.

Dir

ecto

ries

shou

ldin

clud

ea

file

inth

emca

lled

__in

it__.

py,

whi

chsh

ould

prob

ably

incl

ude

the

othe

rfile

sin

the

dire

ctor

y.

Cre

atin

ga

DL

Lth

atin

terf

aces

with

Pyth

onis

cove

red

inan

othe

rsec

tion.

Page 191: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

18.2

Cre

atin

ga

Mod

ule

18.2

.1Fr

oma

File

The

easi

estw

ayto

crea

tea

mod

ule

byha

ving

afil

eca

lled

mym

od.p

yei

ther

ina

dire

ctor

yre

cogn

ized

byth

ePY

TH

ON

PAT

Hva

riab

leor

(eve

nea

sier

)in

the

sam

edi

rect

ory

whe

reyo

uar

ew

orki

ng.

Ifyo

uha

veth

efo

llow

ing

file

mym

od.p

y

class

Object1:

def__init__(self):

self.name

='object

1'

you

can

alre

ady

impo

rtth

is"m

odul

e"an

dcr

eate

inst

ance

sof

the

obje

ctO

b-je

ct1.

import

mymod

myobject

=mymod.Object1()

Page 192: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

from

mymod

import

*myobject

=Object1()

18.2

.2Fr

oma

Dir

ecto

ry

Itis

notf

easi

ble

for

larg

erpr

ojec

tsto

keep

allc

lass

esin

asi

ngle

file.

Itis

ofte

nea

sier

tost

ore

allfi

les

indi

rect

orie

san

dlo

adal

lfile

sw

ithon

eco

mm

and.

Eac

hdi

rect

ory

need

sto

have

a__init__.py

file

whi

chco

ntai

nspy

thon

com

man

dsth

atar

eex

ecut

edup

onlo

adin

gth

edi

rect

ory.

Supp

ose

we

have

two

mor

eob

ject

sca

lledObject2

andObject3

and

we

wan

tto

load

allt

hree

obje

cts

with

one

com

man

d.W

eth

encr

eate

adi

rect

ory

calle

dm

ymod

and

we

stor

eth

ree

files

calle

dObject1.py

,Object2.py

andObject3.py

init.

Thes

efil

esw

ould

then

cont

ain

one

obje

ctpe

rfile

but

this

notr

equi

red

(alth

ough

itad

dscl

arity

).W

ew

ould

then

wri

teth

efo

llow

ing

__init__.py

file:

from

Object1

import

*

Page 193: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

from

Object2

import

*from

Object3

import

*

__all__

=["Object1",

"Object2",

"Object3"]

The

first

thre

eco

mm

ands

tell

pyth

onw

hatt

odo

whe

nso

meb

ody

load

sth

em

odul

e.T

hela

stst

atem

ent

defin

ing

__al

l__t

ells

pyth

onw

hat

todo

whe

nso

meb

ody

exec

utes

from

mym

odim

port

*.U

sual

lyw

ew

antt

ous

epa

rts

ofa

mod

ule

inot

her

part

sof

am

odul

e,e.

g.w

ew

antt

ous

eO

bjec

t1in

Obj

ect2

.W

eca

ndo

this

easi

lyw

ithan

from

.im

port

*co

mm

and

asth

efo

llow

ing

file

Obj

ect2

.py

show

s:

from

.import

*

class

Object2:

def__init__(self):

self.name

='object

2'

self.otherObject

=Object1()

We

can

now

star

tpyt

hon

and

impo

rtm

ymod

asw

eha

vein

the

prev

ious

sect

ion.

Page 194: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

18.3

Ext

erna

llin

ks

•Py

thon

Doc

umen

tatio

n1

1http://docs.python.org/tutorial/modules.html

Page 195: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 196: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

19C

lass

es

Cla

sses

are

aw

ayof

aggr

egat

ing

sim

ilard

ata

and

func

tions

.Acl

assi

sbas

ical

lya

scop

ein

side

whi

chva

rious

code

(esp

ecia

llyfu

nctio

nde

finiti

ons)

isex

ecut

ed,

and

the

loca

lsto

this

scop

ebe

com

eat

trib

utes

ofth

ecl

ass,

and

ofan

yob

ject

sco

nstru

cted

byth

iscl

ass.

An

obje

ctco

nstru

cted

bya

clas

sis

calle

dan

inst

ance

ofth

atcl

ass.

19.0

.1D

efini

nga

Cla

ss

Tode

fine

acl

ass,

use

the

follo

win

gfo

rmat

:

189

Page 197: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

class

ClassName:

...

...

The

capi

taliz

atio

nin

this

clas

sde

finiti

onis

the

conv

entio

n,bu

tis

notr

equi

red

byth

ela

ngua

ge.

19.0

.2In

stan

ceC

onst

ruct

ion

The

clas

sis

aca

llabl

eob

ject

that

cons

truc

tsan

inst

ance

ofth

ecl

ass

whe

nca

lled.

Toco

nstr

ucta

nin

stan

ceof

the

clas

s,Fo

o,"c

all"

the

clas

sob

ject

:

f=

Foo()

Thi

sco

nstr

ucts

anin

stan

ceof

clas

sFo

oan

dcr

eate

sa

refe

renc

eto

itin

f.

Page 198: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

19.0

.3C

lass

Mem

bers

Inor

dert

oac

cess

the

mem

bero

fan

inst

ance

ofa

clas

s,us

eth

esy

ntax

<cla

ssin

stan

ce>.

<mem

ber>

.It

isal

sopo

ssib

leto

acce

ssth

em

embe

rsof

the

clas

sde

finiti

onw

ith<c

lass

nam

e>.<

mem

ber>

.

Met

hods

Am

etho

dis

afu

nctio

nw

ithin

acl

ass.

The

first

argu

men

t(m

etho

dsm

ust

alw

ays

take

atle

asto

near

gum

ent)

isal

way

sth

ein

stan

ceof

the

clas

son

whi

chth

efu

nctio

nis

invo

ked.

Fore

xam

ple

>>>

classFoo:

...

defsetx(self,

x):

...

self.x

=x

...

defbar(self):

...

print

self.x

Page 199: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Ifth

isco

dew

ere

exec

uted

,not

hing

wou

ldha

ppen

,atl

east

until

anin

stan

ceof

Foo

wer

eco

nstr

ucte

d,an

dth

enba

rwer

eca

lled

onth

atin

stan

ce.

Invo

king

Met

hods

Cal

ling

am

etho

dis

muc

hlik

eca

lling

afu

nctio

n,bu

tins

tead

ofpa

ssin

gth

ein

stan

ceas

the

first

para

met

erlik

eth

elis

toff

orm

alpa

ram

eter

ssu

gges

ts,u

seth

efu

nctio

nas

anat

trib

ute

ofth

ein

stan

ce.

>>>

f.setx(5)

>>>

f.bar()

Thi

sw

illou

tput

5

Page 200: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Itis

poss

ible

toca

llth

em

etho

don

anar

bitra

ryob

ject

,by

usin

git

asan

attri

bute

ofth

ede

finin

gcl

ass

inst

ead

ofan

inst

ance

ofth

atcl

ass,

like

so:

>>>

Foo.setx(f,5)

>>>

Foo.bar(f)

Thi

sw

illha

veth

esa

me

outp

ut.

Dyn

amic

Cla

ssSt

ruct

ure

As

show

nby

the

met

hod

setx

abov

e,th

em

embe

rsof

aPy

thon

clas

sca

nch

ange

durin

gru

ntim

e,no

tjus

tthe

irva

lues

,unl

ike

clas

ses

inla

ngua

ges

like

Cor

Java

.W

eca

nev

ende

lete

f.xaf

terr

unni

ngth

eco

deab

ove.

>>>

delf.x

>>>

f.bar()

Page 201: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?File

"<stdin>",

line

5,

in

bar

AttributeError:

Foo

instance

has

no

attribute

'x'

Ano

ther

effe

ctof

this

isth

atw

eca

nch

ange

the

defin

ition

ofth

eFo

ocl

ass

duri

ngpr

ogra

mex

ecut

ion.

Inth

eco

debe

low

,we

crea

tea

mem

bero

fthe

Foo

clas

sde

finiti

onna

med

y.If

we

then

crea

tea

new

inst

ance

ofFo

o,it

will

now

have

this

new

mem

ber.

>>>

Foo.y

=10

>>>

g=

Foo()

>>>

g.y

10 Vie

win

gC

lass

Dic

tiona

ries

Page 202: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

At

the

hear

tof

all

this

isa

dict

iona

ry1

that

can

beac

cess

edby

"var

s(C

lass

Nam

e)"

>>>

vars(g)

{} Atfi

rst,

this

outp

utm

akes

nose

nse.

We

just

saw

that

gha

dth

em

embe

ry,s

ow

hyis

n'ti

tin

the

mem

berd

ictio

nary

?If

you

rem

embe

r,th

ough

,we

puty

inth

ecl

ass

defin

ition

,Foo

,not

g.

>>>

vars(Foo)

{'y':

10,

'bar':

<function

bar

at

0x4d6a3c>,

'__module__':

'__main__',

'setx':

<function

setx

at

0x4d6a04>,

'__doc__':

None}

And

ther

ew

eha

veal

lthe

mem

bers

ofth

eFo

ocl

ass

defin

ition

.Whe

nPy

thon

chec

ksfo

rg.

mem

ber,

itfir

stch

ecks

g's

vars

dict

iona

ryfo

r"m

embe

r,"th

en

1C

hapt

er10

onpa

ge99

Page 203: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Foo.

Ifw

ecr

eate

ane

wm

embe

rofg

,itw

illbe

adde

dto

g's

dict

iona

ry,b

utno

tFo

o's.

>>>

g.setx(5)

>>>

vars(g)

{'x':

5}

Not

eth

atif

we

now

assi

gna

valu

eto

g.y,

we

are

nota

ssig

ning

that

valu

eto

Foo.

y.Fo

o.y

will

still

be10

,but

g.y

will

now

over

ride

Foo.

y

>>>

g.y

=9

>>>

vars(g)

{'y':

9,

'x':

5}

>>>

vars(Foo)

{'y':

10,

'bar':

<function

bar

at

0x4d6a3c>,

'__module__':

'__main__',

'setx':

<function

setx

at

0x4d6a04>,

'__doc__':

None}

Sure

enou

gh,i

fwe

chec

kth

eva

lues

:

>>>

g.y

Page 204: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9 >>>

Foo.y

10 Not

eth

atf.y

will

also

be10

,as

Pyth

onw

on't

find

'y'i

nva

rs(f

),so

itw

illge

tth

eva

lue

of'y

'fro

mva

rs(F

oo).

Som

em

ayha

veal

sono

ticed

that

the

met

hods

inFo

oap

pear

inth

ecl

ass

dict

iona

ryal

ong

with

the

xan

dy.

Ifyo

ure

mem

berf

rom

the

sect

ion

onla

mbd

afo

rms2 ,

we

can

trea

tfu

nctio

nsju

stlik

eva

riab

les.

Thi

sm

eans

that

we

can

assi

gnm

etho

dsto

acl

assd

urin

gru

ntim

ein

the

sam

ew

ayw

eas

sign

edva

riabl

es.

Ifyo

udo

this

,tho

ugh,

rem

embe

rtha

tifw

eca

lla

met

hod

ofa

clas

sin

stan

ce,

the

first

para

met

erpa

ssed

toth

em

etho

dw

illal

way

sbe

the

clas

sin

stan

ceits

elf.

Cha

ngin

gC

lass

Dic

tiona

ries

2C

hapt

er14

.0.5

onpa

ge14

8

Page 205: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

We

can

also

acce

ssth

em

embe

rsdi

ctio

nary

ofa

clas

sus

ing

the

__di

ct__

-m

embe

roft

hecl

ass.

>>>

g.__dict__

{'y':

9,

'x':

5}

Ifw

ead

d,re

mov

e,or

chan

geke

y-va

lue

pair

sfr

omg.

__di

ct__

,thi

sha

sth

esa

me

effe

ctas

ifw

eha

dm

ade

thos

ech

ange

sto

the

mem

bers

ofg.

>>>

g.__dict__['z']

=-4

>>>

g.z

-4 19

.0.4

New

Styl

eC

lass

es

New

styl

ecl

asse

sw

ere

intr

oduc

edin

pyth

on2.

2.A

new

-sty

lecl

ass

isa

clas

sth

atha

sa

built

-in

asits

base

,mos

tcom

mon

lyob

ject

.Ata

low

leve

l,a

maj

ordi

ffer

ence

betw

een

old

and

new

clas

ses

isth

eirt

ype.

Old

clas

sin

stan

ces

wer

e

Page 206: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

allo

ftyp

einstance

.New

styl

ecl

ass

inst

ance

sw

illre

turn

the

sam

eth

ing

asx.

__cl

ass_

_for

thei

rtyp

e.T

his

puts

user

defin

edcl

asse

son

ale

velp

layi

ngfie

ldw

ithbu

ilt-i

ns.

Old

/Cla

ssic

clas

ses

are

slat

edto

disa

ppea

rin

Pyth

on3.

With

this

inm

ind

alld

evel

opm

ents

houl

dus

ene

wst

yle

clas

ses.

New

Styl

ecl

asse

sal

soad

dco

nstr

ucts

like

prop

ertie

san

dst

atic

met

hods

fam

iliar

toJa

vapr

ogra

mm

ers.

Old

/Cla

ssic

Cla

ss

>>>

classClassicFoo:

...

def__init__(self):

...

pass

New

Styl

eC

lass

>>>

classNewStyleFoo(object):

...

def__init__(self):

...

pass

Page 207: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Prop

ertie

s

Prop

ertie

sar

eat

trib

utes

with

gette

rand

sette

rmet

hods

.

>>>

classSpamWithProperties(object):

...

def__init__(self):

...

self.__egg

="MyEgg"

...

defget_egg(self):

...

return

self.__egg

...

defset_egg(self,

egg):

...

self.__egg

=egg

...

egg

=property(get_egg,

set_egg)

>>>

sp

=SpamWithProperties()

>>>

sp.egg

'MyEgg'

>>>

sp.egg

="Eggs

With

Spam"

>>>

sp.egg

'Eggs

With

Spam'

>>>

and

sinc

ePy

thon

2.6,

with

@pr

oper

tyde

cora

tor

Page 208: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

classSpamWithProperties(object):

...

def__init__(self):

...

self.__egg

="MyEgg"

...

@property

...

defegg(self):

...

return

self.__egg

...

@egg.setter

...

defegg(self,

egg):

...

self.__egg

=egg

Stat

icM

etho

ds

Stat

icm

etho

dsin

Pyth

onar

eju

stlik

eth

eirc

ount

erpa

rts

inC

++or

Java

.Sta

ticm

etho

dsha

veno

"sel

f"ar

gum

enta

nddo

n'tr

equi

reyo

uto

inst

antia

teth

ecl

ass

befo

reus

ing

them

.The

yca

nbe

defin

edus

ing

stat

icm

etho

d()

>>>

classStaticSpam(object):

...

defStaticNoSpam():

...

print

"You

can't

have

have

the

spam,

spam,

eggs

and

spam

without

any

spam...

that's

disgusting"

Page 209: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

...

NoSpam

=staticmethod(StaticNoSpam)

>>>

StaticSpam.NoSpam()

'You

can\'t

have

have

the

spam,

spam,

eggs

and

spam

without

any

spam...

that\'s

disgusting'

The

yca

nal

sobe

defin

edus

ing

the

func

tion

deco

rato

r@st

atic

met

hod.

>>>

classStaticSpam(object):

...

@staticmethod

...

defStaticNoSpam():

...

print

"You

can't

have

have

the

spam,

spam,

eggs

and

spam

without

any

spam...

that's

disgusting"

19.0

.5In

heri

tanc

e

Like

allo

bjec

torie

nted

lang

uage

s,Py

thon

prov

ides

fori

nher

itanc

e.In

herit

ance

isa

sim

ple

conc

eptb

yw

hich

acl

ass

can

exte

ndth

efa

cilit

ies

ofan

othe

rcla

ss,

orin

Pyth

on's

case

,mul

tiple

othe

rcla

sses

.Use

the

follo

win

gfo

rmat

fort

his:

Page 210: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

class

ClassName(superclass1,superclass2,superclass3,...):

...

The

subc

lass

will

then

have

allt

hem

embe

rsof

itssu

perc

lass

es.I

fam

etho

dis

defin

edin

the

subc

lass

and

inth

esu

perc

lass

,the

mem

ber

inth

esu

bcla

ssw

illov

erri

deth

eon

ein

the

supe

rcla

ss.I

nor

dert

ous

eth

em

etho

dde

fined

inth

esu

perc

lass

,iti

sne

cess

ary

toca

llth

em

etho

das

anat

tribu

teon

the

defin

ing

clas

s,as

inFo

o.se

tx(f

,5)a

bove

:

>>>

classFoo:

...

defbar(self):

...

print

"I'm

doing

Foo.bar()"

...

x=

10

...

>>>

classBar(Foo):

...

defbar(self):

...

print

"I'm

doing

Bar.bar()"

...

Foo.bar(self)

...

y=

9...

>>>

g=

Bar()

Page 211: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

Bar.bar(g)

I'm

doing

Bar.bar()

I'm

doing

Foo.bar()

>>>

g.y

9 >>>

g.x

10 Onc

eag

ain,

we

can

see

wha

t'sgo

ing

onun

dert

heho

odby

look

ing

atth

ecl

ass

dict

iona

ries

.

>>>

vars(g)

{}>>>

vars(Bar)

{'y':

9,

'__module__':

'__main__',

'bar':

<function

bar

at

0x4d6a04>,

'__doc__':

None}

>>>

vars(Foo)

{'x':

10,

'__module__':

'__main__',

'bar':

<function

bar

at

0x4d6994>,

'__doc__':

None}

Page 212: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Whe

nw

eca

llg.

x,it

first

look

sin

the

vars

(g)

dict

iona

ry,a

sus

ual.

Als

oas

abov

e,it

chec

ksva

rs(B

ar)n

ext,

sinc

eg

isan

inst

ance

ofB

ar.H

owev

er,t

hank

sto

inhe

rita

nce,

Pyth

onw

illch

eck

vars

(Foo

)ifi

tdoe

sn't

find

xin

vars

(Bar

).

19.0

.6Sp

ecia

lMet

hods

The

rear

ea

num

ber

ofm

etho

dsw

hich

have

rese

rved

nam

esw

hich

are

used

fors

peci

alpu

rpos

eslik

em

imic

king

num

eric

alor

cont

aine

rope

ratio

ns,a

mon

got

her

thin

gs.

All

ofth

ese

nam

esbe

gin

and

end

with

two

unde

rsco

res.

Itis

conv

entio

nth

atm

etho

dsbe

ginn

ing

with

asi

ngle

unde

rsco

rear

e'p

rivat

e'to

the

scop

eth

eyar

ein

trod

uced

with

in.

Initi

aliz

atio

nan

dD

elet

ion

__in

it__

One

ofth

ese

purp

oses

isco

nstr

uctin

gan

inst

ance

,and

the

spec

ialn

ame

for

Page 213: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

this

is'_

_ini

t__'

.__

init_

_()

isca

lled

befo

rean

inst

ance

isre

turn

ed(i

tis

not

nece

ssar

yto

retu

rnth

ein

stan

cem

anua

lly).

As

anex

ampl

e,

class

A:

def__init__(self):

print'A.__init__()'

a=

A()

outp

uts

A.__init__()

__in

it__(

)can

take

argu

men

ts,i

nw

hich

case

itis

nece

ssar

yto

pass

argu

men

tsto

the

clas

sin

orde

rto

crea

tean

inst

ance

.For

exam

ple,

class

Foo:

def__init__

(self,

printme):

printprintme

foo

=Foo('Hi!')

Page 214: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

outp

uts

Hi!

Her

eis

anex

ampl

esh

owin

gth

edi

ffer

ence

betw

een

usin

g__

init_

_()a

ndno

tus

ing

__in

it__(

):

class

Foo:

def__init__

(self,

x):

printx

foo

=Foo('Hi!')

class

Foo2:

defsetx(self,

x):

printx

f=

Foo2()

Foo2.setx(f,'Hi!')

outp

uts

Page 215: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Hi!

Hi!

__de

l__

Sim

ilarl

y,'_

_del

__'i

sca

lled

whe

nan

inst

ance

isde

stro

yed;

e.g.

whe

nit

isno

long

erre

fere

nced

.

Rep

rese

ntat

ion

Page 216: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

__st

r__

Con

vert

ing

anob

ject

toa

stri

ng,a

sw

ithth

epr

ints

tate

men

torw

ithth

est

r()c

onve

rsio

nfu

nctio

n,ca

nbe

over

ridd

enby

over

ridi

ng__

str_

_.U

sual

ly,_

_str

__re

turn

sa

form

atte

dve

rsio

nof

the

obje

cts

cont

ent.

Thi

sw

illN

OT

usua

llybe

som

ethi

ngth

atca

nbe

exec

uted

.Fo

rexa

mpl

e:

classBar:

def__init__

(self,

iamthis):

self.iamthis

=iamthis

def__str__

(self):

return

self.iamthis

bar

=Bar('apple')

printbar

outp

uts

appl

e

__re

pr__

Thi

sfu

nctio

nis

muc

hlik

e__

str_

-_(

).If

__st

r__i

sno

tpre

sent

but

this

one

is,t

his

func

tion'

sou

tput

isus

edin

stea

dfo

rpri

ntin

g.__

repr

_-_i

sus

edto

retu

rna

repr

esen

tatio

nof

the

obje

ctin

stri

ngfo

rm.I

nge

nera

l,it

can

beex

ecut

edto

get

back

the

orig

inal

obje

ct.

Fore

xam

ple:

classBar:

def__init__

(self,

iamthis):

self.iamthis

=iamthis

def__repr__(self):

return

"Bar('%s')"

%self.iamthis

bar

=Bar('apple')

bar

outp

uts

(not

eth

edi

ffer

ence

:now

isno

tnec

essa

ryto

puti

tins

ide

apr

int)

Bar

('app

le')

Stri

ngR

epre

sent

atio

nO

ver-

ride

Func

tions

Func

tion

Ope

rato

r__

str_

_st

r(A

)__

repr

__re

pr(A

)__

unic

ode_

_un

icod

e(x)

(2.x

only

)

Page 217: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Att

ribu

tes

Page 218: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

__se

tatt

r__

Thi

sis

the

func

tion

whi

chis

inch

arge

ofse

tting

attr

ibut

esof

acl

ass.

Itis

prov

ided

with

the

nam

ean

dva

lue

ofth

eva

riab

les

bein

gas

sign

ed.E

ach

clas

s,of

cour

se,

com

esw

itha

defa

ult_

_set

attr

__-

whi

chsi

mpl

yse

tsth

eva

lue

ofth

eva

riab

le,b

utw

eca

nov

erri

deit.

>>>classUnchangable:

...

def__setattr__(self,

name,

value):

...

print

"Nice

try"

...

>>>

u=

Unchangable()

>>>

u.x

=9

Nicetry

>>>

u.x

Trac

ebac

k(m

ostr

ecen

tcal

llas

t):

File

"<st

din>

",lin

e1,

in?

Attr

ibu-

teE

rror

:Unc

hang

able

inst

ance

has

noat

trib

ute

'x'

__ge

tatt

r___

Sim

ilart

o__

seta

ttr__

,exc

eptt

his

func

tion

isca

lled

whe

nw

etr

yto

acce

ssa

clas

sm

embe

r,an

dth

ede

faul

tsim

ply

retu

rns

the

valu

e.

>>>classHiddenMembers:

...

def

__getattr__(self,

name):

...

return"You

don't

get

to

see

"+

name

...

>>>

h=

HiddenMembers()

>>>

h.anything

"You

don't

get

to

see

anything"

__de

latt

r__

Thi

sfu

nctio

nis

calle

dto

dele

tean

attr

ibut

e.

>>>classPermanent:

...

def

__delattr__(self,

name):

...

printname,

"cannot

be

deleted"

...

>>>

p=

Permanent()

>>>

p.x

=9

>>>delp.x

xcannot

be

deleted

>>>

p.x

9

Att

ribu

teO

verr

ide

Func

tions

Func

tion

Indi

rect

form

Dir

ect

Form

__-

geta

ttr__

geta

ttr(A

,B

)A

.B

__-

seta

ttr__

seta

ttr(A

,B

,C)

A.B

=C

__-

dela

ttr__

dela

ttr(A

,B

)de

lA.B

Page 219: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Ope

rato

rO

verl

oadi

ng

Ope

rato

rove

rload

ing

allo

ws

usto

use

the

built

-inPy

thon

synt

axan

dop

erat

ors

toca

llfu

nctio

nsw

hich

we

defin

e.

Bin

ary

Ope

rato

rs

Page 220: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

3C

hapt

er12

.6on

page

122

4C

hapt

er12

.6on

page

122

Page 221: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Ifa

clas

sha

sth

e__

add_

_fun

ctio

n,w

eca

nus

eth

e'+

'ope

rato

rto

add

inst

ance

sof

the

clas

s.T

his

will

call

__ad

d__w

ithth

etw

oin

stan

ces

ofth

ecl

ass

pass

edas

para

met

ers,

and

the

retu

rnva

lue

will

beth

ere

sult

ofth

ead

ditio

n.

>>>classFakeNumber:

...

n=

5...

def

__add__(A,B):

...

returnA.n

+B.n

...

>>>

c=

FakeNumber()

>>>

d=

FakeNumber()

>>>

d.n

=7

>>>

c+

d12 To

over

ride

the

augm

ente

das

sign

-m

ent3

oper

ator

s,m

erel

yad

d'i'

infr

onto

fthe

norm

albi

nary

oper

ator

,i.e

.for

'+='

use

'__i

add_

_'in

stea

dof

'__a

dd__

'.T

hefu

nctio

nw

illbe

give

non

ear

gum

ent,

whi

chw

illbe

the

obje

cton

the

righ

tsid

eof

the

augm

ente

das

sign

men

tope

rato

r.T

here

turn

edva

lue

ofth

efu

nctio

nw

illth

enbe

assi

gned

toth

eob

ject

onth

ele

ftof

the

oper

ator

.

>>>

c.__imul__

=lambdaB:

B.n

-6

>>>

c*=

d>>>

c1 It

isim

port

antt

ono

teth

atth

eau

g-m

ente

das

sign

men

t4op

erat

ors

will

also

use

the

norm

alop

erat

orfu

nc-

tions

ifth

eau

gmen

ted

oper

ator

func

tion

hasn

'tbe

ense

tdir

ectly

.T

his

will

wor

kas

expe

cted

,with

"__a

dd__

"be

ing

calle

dfo

r"+=

"an

dso

on.

>>>

c=

FakeNumber()

>>>

c+=

d>>>

c12

Bin

ary

Ope

rato

rO

verr

ide

Func

tions

Func

tion

Ope

rato

r__

add_

_A

+B

__su

b__

A-B

__m

ul__

A*

B__

true

div_

_A

/B__

floor

div_

_A

//B

__m

od__

A%

B__

pow

__A

**B

__an

d__

A&

B__

or__

A|B

__xo

r__

AˆB

__eq

__A

==B

__ne

__A

!=B

__gt

__A

>B

__lt_

_A

<B

__ge

__A

>=B

__le

__A

<=B

__ls

hift

__A

<<B

__rs

hift

__A

>>B

__co

ntai

ns__

Ain

BA

noti

nB

Page 222: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Una

ryO

pera

tors

Una

ryop

erat

ors

will

bepa

ssed

sim

ply

the

inst

ance

ofth

ecl

ass

that

they

are

calle

don

.

>>>

FakeNumber.__neg__

=lambda

A:

A.n

+6

>>>

-d

13

Una

ryO

pera

tor

Ove

rrid

eFu

nctio

nsFu

nctio

nO

pera

tor

__po

s__

+A__

neg_

_-A

__in

v__

˜A__

abs_

_ab

s(A

)__

len_

_le

n(A

)

Item

Ope

rato

rs

Page 223: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Itis

also

poss

ible

inPy

thon

toov

erri

deth

ein

dexi

ngan

dsl

icin

g5

oper

ator

s.T

his

allo

ws

usto

use

the

clas

s[i]

and

clas

s[a:

b]sy

ntax

onou

row

nob

ject

s.T

hesi

mpl

estf

orm

ofite

mop

erat

oris

__ge

titem

__.T

his

take

sas

apa

ram

eter

the

inst

ance

ofth

ecl

ass,

then

the

valu

eof

the

inde

x.

>>>classFakeList:

...

def

__getitem__(self,index):

...

returnindex*

2...

>>>

f=

FakeList()

>>>

f['a']

'aa'

We

can

also

defin

ea

func

tion

for

the

synt

axas

soci

ated

with

assi

gn-

ing

ava

lue

toan

item

.The

para

m-

eter

sfo

rthi

sfu

nctio

nin

clud

eth

eva

lue

bein

gas

sign

ed,i

nad

ditio

nto

the

para

met

ers

from

__ge

titem

__

>>>classFakeList:

...

def

__setitem__(self,index,value):

...

self.string

=index

+"

is

now

"+

value

...

>>>

f=

FakeList()

>>>

f['a']

='gone'

>>>

f.string

'a

is

now

gone'

We

can

doth

esa

me

thin

gw

ithsl

ices

.Onc

eag

ain,

each

synt

axha

sa

diff

eren

tpar

amet

erlis

tass

oci-

ated

with

it.

>>>classFakeList:

...

def

__getslice___(self,start,end):

...

returnstr(start)

+"

to

"+

str(end)

...

>>>

f=

FakeList()

>>>

f[1:4]

'1

to

4'

Kee

pin

min

dth

aton

eor

both

ofth

est

arta

nden

dpa

ram

eter

sca

nbe

blan

kin

slic

esy

ntax

.Her

e,Py

thon

has

defa

ultv

alue

forb

oth

the

star

tan

dth

een

d,as

show

belo

w.

>>

f[:]

'0

to

2147483647'

Not

eth

atth

ede

faul

tval

uefo

rthe

end

ofth

esl

ice

show

nhe

reis

sim

-pl

yth

ela

rges

tpos

sibl

esi

gned

in-

tege

ron

a32

-bit

syst

em,a

ndm

ayva

ryde

pend

ing

onyo

ursy

stem

and

Cco

mpi

ler.

•__

sets

lice_

_has

the

para

met

ers

(sel

f,sta

rt,e

nd,v

alue

)W

eal

soha

veop

erat

ors

ford

elet

ing

item

san

dsl

ices

.•

__de

litem

__ha

sth

epa

ram

eter

s(s

elf,i

ndex

)•

__de

lslic

e__h

asth

epa

ram

eter

s(s

elf,s

tart

,end

)N

ote

that

thes

ear

eth

esa

me

as__

getit

em__

and

__ge

tslic

e__.

Item

Ope

rato

rO

verr

ide

Func

-tio

nsFu

nctio

nO

pera

tor

__ge

titem

__C

[i]

__se

titem

__C

[i]=

v__

delit

em__

delC

[i]

__ge

tslic

e__

C[s

:e]

__se

tslic

e__

C[s

:e]=

v__

dels

lice_

_de

lC[s

:e]

5C

hapt

er8.

1.1

onpa

ge56

Page 224: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Oth

erO

verr

ides

Page 225: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Oth

erO

verr

ide

Func

tions

Func

tion

Ope

rato

r__

cmp_

_cm

p(x,

y)__

hash

__ha

sh(x

)__

nonz

ero_

_bo

ol(x

)__

call_

_f(

x)__

iter_

_ite

r(x)

__re

vers

ed__

reve

rsed

(x)

(2.6

+)__

divm

od__

divm

od(x

,y)

__in

t__

int(

x)__

long

__lo

ng(x

)__

float

__flo

at(x

)__

com

plex

__co

mpl

ex(x

)__

hex_

_he

x(x)

__oc

t__

oct(

x)__

inde

x__

__co

py__

copy

.cop

y(x)

__de

epco

py__

copy

.dee

pcop

y(x)

__si

zeof

__sy

s.ge

tsiz

eof(

x)(2

.6+)

__tr

unc_

_m

ath.

trun

c(x)

(2.6

+)__

form

at__

form

at(x

,...)

(2.6

+)

Page 226: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

19.0

.7Pr

ogra

mm

ing

Prac

tices

The

flexi

bilit

yof

pyth

oncl

asse

sm

eans

that

clas

ses

can

adop

tava

ried

seto

fbe

havi

ors.

For

the

sake

ofun

ders

tand

abili

ty,h

owev

er,i

t'sbe

stto

use

man

yof

Pyth

on's

tool

ssp

arin

gly.

Try

tode

clar

eal

lmet

hods

inth

ecl

ass

defin

ition

,an

dal

way

sus

eth

e<c

lass

>.<m

embe

r>sy

ntax

inst

ead

of__

dict

__w

hene

ver

poss

ible

.L

ook

atcl

asse

sin

C++

6an

dJa

va7

tose

ew

hatm

ostp

rogr

amm

ers

will

expe

ctfr

oma

clas

s.

6http://en.wikibooks.org/wiki/C%2B%2B%20Programming%

2FClasses

7http://en.wikipedia.org/wiki/Class%20%28computer%

20science%29%23Java

Page 227: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Enc

apsu

latio

n

Sinc

eal

lpyt

hon

mem

bers

ofa

pyth

oncl

assa

reac

cess

ible

byfu

nctio

ns/m

etho

dsou

tsid

eth

ecl

ass,

ther

eis

now

ayto

enfo

rce

enca

psul

atio

n8sh

orto

fove

rrid

ing

__ge

tattr

__,_

_set

attr

__an

d__

dela

ttr__

.Gen

eral

prac

tice,

how

ever

,is

fort

hecr

eato

rofa

clas

sor

mod

ule

tosi

mpl

ytru

stth

atus

ers

will

use

only

the

inte

nded

inte

rfac

ean

dav

oid

limiti

ngac

cess

toth

ew

orki

ngs

ofth

em

odul

efo

rthe

sake

ofus

ers

who

done

edto

acce

ssit.

Whe

nus

ing

part

sof

acl

ass

orm

odul

eot

hert

han

the

inte

nded

inte

rfac

e,ke

epin

min

dth

atth

eth

ose

parts

may

chan

gein

late

rver

sion

sof

the

mod

ule,

and

you

may

even

caus

eer

rors

orun

defin

edbe

havi

ors

inth

em

odul

e.

8http://en.wikipedia.org/wiki/Information%20Hiding

Page 228: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Doc

Stri

ngs

Whe

nde

finin

ga

clas

s,it

isco

nven

tion

todo

cum

entt

hecl

ass

usin

ga

stri

nglit

eral

atth

est

arto

fthe

clas

sde

finiti

on.T

his

stri

ngw

illth

enbe

plac

edin

the

__do

c__a

ttrib

ute

ofth

ecl

ass

defin

ition

.

>>>

classDocumented:

...

"""This

is

adocstring"""

...

defexplode(self):

...

"""

...

This

method

is

documented,

too!

The

coder

is

really

serious

about

...

making

this

class

usable

by

others

who

don't

know

the

code

as

well

...

as

he

does.

...

...

"""

...

print

"boom"

>>>

d=

Documented()

>>>

d.__doc__

'This

is

adocstring'

Page 229: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Doc

stri

ngs

are

ave

ryus

eful

way

todo

cum

enty

ourc

ode.

Eve

nif

you

neve

rw

rite

asi

ngle

piec

eof

sepa

rate

docu

men

tatio

n(a

ndle

t'sad

mit

it,do

ing

sois

the

low

estp

rior

ityfo

rman

yco

ders

),in

clud

ing

info

rmat

ive

docs

trin

gsin

your

clas

ses

will

goa

long

way

tow

ard

mak

ing

them

usab

le.

Seve

ralt

ools

exis

tfor

turn

ing

the

docs

tring

sin

Pyth

onco

dein

tore

adab

leA

PIdo

cum

enta

tion,

e.g.

,E

pyD

oc9 .

Don

'tju

stst

opat

docu

men

ting

the

clas

sde

finiti

on,e

ither

.Eac

hm

etho

din

the

clas

ssh

ould

have

itsow

ndo

cstr

ing

asw

ell.

Not

eth

atth

edo

cstr

ing

for

the

met

hod

expl

ode

inth

eex

ampl

ecl

ass

Doc

umen

ted

abov

eha

sa

fair

lyle

ngth

ydo

cstri

ngth

atsp

ans

seve

rall

ines

.Its

form

attin

gis

inac

cord

ance

with

the

styl

esu

gges

tions

ofPy

thon

'scr

eato

r,G

uido

van

Ros

sum

.

9http://epydoc.sourceforge.net/using.html

Page 230: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Add

ing

met

hods

atru

ntim

e

Toa

clas

s

Itis

fairl

yea

syto

add

met

hods

toa

clas

sat

runt

ime.

Lets

assu

me

that

we

have

acl

ass

calle

dSp

aman

da

func

tion

cook

.We

wan

tto

beab

leto

use

the

func

tion

cook

onal

lins

tanc

esof

the

clas

sSp

am:

class

Spam:

def__init__(self):

self.myeggs

=5

def

cook(self):

print"cooking

%s

eggs"

%self.myeggs

Spam.cook

=cook

#add

the

function

to

the

class

Spam

eggs

=Spam()

#NOW

create

anew

instance

of

Spam

eggs.cook()

#and

we

are

ready

to

cook!

Page 231: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illou

tput

cooking

5eggs

Toan

inst

ance

ofa

clas

s

Itis

abi

tmor

etr

icky

toad

dm

etho

dsto

anin

stan

ceof

acl

ass

that

has

alre

ady

been

crea

ted.

Lets

assu

me

agai

nth

atw

eha

vea

clas

sca

lled

Spam

and

we

have

alre

ady

crea

ted

eggs

.But

then

we

notic

eth

atw

ew

ante

dto

cook

thos

eeg

gs,

butw

edo

notw

antt

ocr

eate

ane

win

stan

cebu

trat

heru

seth

eal

read

ycr

eate

don

e:

class

Spam:

def__init__(self):

self.myeggs

=5

eggs

=Spam()

Page 232: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

def

cook(self):

print"cooking

%s

eggs"

%self.myeggs

import

types

f=

types.MethodType(cook,

eggs,

Spam)

eggs.cook

=f

eggs.cook()

Now

we

can

cook

oure

ggs

and

the

last

stat

emen

twill

outp

ut:

cooking

5eggs

Usi

nga

func

tion

We

can

also

wri

tea

func

tion

that

will

mak

eth

epr

oces

sof

addi

ngm

etho

dsto

anin

stan

ceof

acl

ass

easi

er.

Page 233: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

def

attach_method(fxn,

instance,

myclass):

f=

types.MethodType(fxn,

instance,

myclass)

setattr(instance,

fxn.__name__,

f)

All

we

now

need

todo

isca

llth

eat

tach

_met

hod

with

the

argu

men

tsof

the

func

tion

we

wan

tto

atta

ch,t

hein

stan

cew

ew

antt

oat

tach

itto

and

the

clas

sth

ein

stan

ceis

deriv

edfr

om.T

hus

ourf

unct

ion

call

mig

htlo

oklik

eth

is:

attach_method(cook,

eggs,

Spam)

Not

eth

atin

the

func

tion

add_

met

hod

we

cann

otw

riteinstance.fxn=

fsi

nce

this

wou

ldad

da

func

tion

calle

dfx

nto

the

inst

ance

.

fr:P

rogr

amm

atio

nPy

thon

/Pro

gram

mat

ion

orie

nté

obje

t10pt

:Pyt

hon/

Con

ceito

sbá

sico

s/C

lass

es11

10http://fr.wikibooks.org/wiki/Programmation%20Python%

2FProgrammation%20orient%E9%20objet

11http://pt.wikibooks.org/wiki/Python%2FConceitos%20b%

E1sicos%2FClasses

Page 234: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

20M

etaC

lass

es

Inpy

thon

,cla

sses

are

them

selv

esob

ject

s.Ju

stas

othe

robj

ects

are

inst

ance

sof

apa

rtic

ular

clas

s,cl

asse

sth

emse

lves

are

inst

ance

sof

am

etac

lass

.

20.0

.8C

lass

Fact

orie

s

The

sim

ples

tuse

ofpy

thon

met

acla

sses

isa

clas

sfa

ctor

y.T

his

conc

eptm

akes

use

ofth

efa

ctth

atcl

ass

defin

ition

sin

pyth

onar

efir

st-c

lass

obje

cts1 .

Such

a

1http://en.wikipedia.org/wiki/First-class%20%28object%29

227

Page 235: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

func

tion

can

crea

teor

mod

ify

acl

ass

defin

ition

,usi

ngth

esa

me

synt

ax2

one

wou

ldno

rmal

lyus

ein

decl

arin

ga

clas

sde

finiti

on.

Onc

eag

ain,

itis

usef

ulto

use

the

mod

elof

clas

ses

asdi

ctio

nari

es3 .

Firs

t,le

t'slo

okat

aba

sic

clas

sfa

ctor

y:

>>>

defStringContainer():

...

#define

aclass

...

classString:

...

content_string

=""

...

deflen(self):

...

return

len(self.content_string)

...

#return

the

class

definition

...

returnString

...

>>>

#create

the

class

definition

...

container_class

=StringContainer()

>>>

>>>

#create

an

instance

of

the

class

...

wrapped_string

=container_class()

>>>

2C

hapt

er19

.0.1

onpa

ge18

93

Cha

pter

19.0

.3on

page

194

Page 236: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

#take

it

for

atest

drive

...

wrapped_string.content_string

='emu

emissary'

>>>

wrapped_string.len()

12 Of

cour

se,

just

like

any

othe

rda

tain

pyth

on,

clas

sde

finiti

ons

can

also

bem

odifi

ed.A

nym

odifi

catio

nsto

attr

ibut

esin

acl

ass

defin

ition

will

bese

enin

any

inst

ance

sof

that

defin

ition

,so

long

asth

atin

stan

ceha

sn't

over

ridd

enth

eat

trib

ute

that

you'

rem

odif

ying

.

>>>

defDeAbbreviate(sequence_container):

...

sequence_container.length

=sequence_container.len

...

delsequence_container.len

...

>>>

DeAbbreviate(container_class)

>>>

wrapped_string.length()

12>>>

wrapped_string.len()

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?AttributeError:

String

instance

has

no

attribute

'len'

Page 237: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

You

can

also

dele

tecl

ass

defin

ition

s,bu

ttha

twill

nota

ffec

tins

tanc

esof

the

clas

s. >>>

del

container_class

>>>

wrapped_string2

=container_class()

Traceback

(most

recent

call

last):

File

"<stdin>",

line

1,

in

?NameError:

name

'container_class'

is

not

defined

>>>

wrapped_string.length()

12

20.0

.9T

hety

peM

etac

lass

The

met

acla

ssfo

rall

stan

dard

pyth

onty

pes

isth

e"t

ype"

obje

ct.

>>>

type(object)

<type

'type'>

>>>

type(int)

<type

'type'>

Page 238: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

type(list)

<type

'type'>

Just

like

list,

inta

ndob

ject

,"ty

pe"

isits

elfa

norm

alpy

thon

obje

ct,a

ndis

itsel

fan

inst

ance

ofa

clas

s.In

this

case

,iti

sin

fact

anin

stan

ceof

itsel

f.

>>>

type(type)

<type

'type'>

Itca

nbe

inst

antia

ted

tocr

eate

new

clas

sob

ject

ssi

mila

rly

toth

ecl

ass

fact

ory

exam

ple

abov

eby

pass

ing

the

nam

eof

the

new

clas

s,th

eba

secl

asse

sto

inhe

ritfr

om,a

nda

dict

iona

ryde

finin

gth

ena

mes

pace

tous

e.

Fori

nsta

nce,

the

code

:

>>>

classMyClass(BaseClass):

...

attribute

=42

Cou

ldal

sobe

wri

tten

as:

Page 239: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

MyClass

=type("MyClass",

(BaseClass,),

{'attribute'

:42})

20.0

.10

Met

acla

sses

Itis

poss

ible

tocr

eate

acl

ass

with

adi

ffer

entm

etac

lass

than

type

byse

tting

its__

met

acla

ss__

attr

ibut

ew

hen

defin

ing.

Whe

nth

isis

done

,the

clas

s,an

dits

subc

lass

will

becr

eate

dus

ing

your

cust

omm

etac

lass

.For

exam

ple

class

CustomMetaclass(type):

def__init__(cls,

name,

bases,

dct):

print"Creating

class

%s

using

CustomMetaclass"

%name

super(CustomMetaclass,

cls).__init__(name,

bases,

dct)

class

BaseClass(object):

__metaclass__

=CustomMetaclass

class

Subclass1(BaseClass):

pass

Page 240: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Thi

sw

illpr

int

Creating

class

BaseClass

using

CustomMetaclass

Creating

class

Subclass1

using

CustomMetaclass

By

crea

ting

acu

stom

met

acla

ssin

this

way

,it

ispo

ssib

leto

chan

geho

wth

ecl

ass

isco

nstr

ucte

d.T

his

allo

ws

you

toad

dor

rem

ove

attr

ibut

esan

dm

etho

ds,r

egis

terc

reat

ion

ofcl

asse

san

dsu

bcla

sses

crea

tion

and

vari

ous

othe

rm

anip

ulat

ions

whe

nth

ecl

ass

iscr

eate

d.

20.0

.11

Mor

ere

sour

ces

•W

ikip

edia

artic

leon

Asp

ectO

rien

ted

Prog

ram

min

g4

•U

nify

ing

type

san

dcl

asse

sin

Pyth

on2.

25

4http://en.wikipedia.org/wiki/Aspect-oriented_programming

5http://www.python.org/2.2/descrintro.html

Page 241: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•O

'Rei

llyA

rtic

leon

Pyth

onM

etac

lass

es6

6http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.

html

Page 242: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

21R

egul

arE

xpre

ssio

n

Pyth

onin

clud

esa

mod

ule

forw

orki

ngw

ithre

gula

rexp

ress

ions

onst

rings

.For

mor

ein

form

atio

nab

outw

ritin

gre

gula

rexp

ress

ions

and

synt

axno

tspe

cific

toPy

thon

,see

the

regu

lar

expr

essi

ons1

wik

iboo

k.Py

thon

'sre

gula

rex

pres

sion

synt

axis

sim

ilart

oPe

rl's2

Tost

artu

sing

regu

lare

xpre

ssio

nsin

your

Pyth

onsc

ript

s,ju

stim

port

the

"re"

mod

ule:

1http://en.wikibooks.org/wiki/regular%20expressions

2http://en.wikibooks.org/wiki/Perl%20Programming%2FRegular%

20Expressions%20Reference

235

Page 243: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

import

re

21.1

Patt

ern

obje

cts

Ifyo

u're

goin

gto

beus

ing

the

sam

ere

gexp

mor

eth

anon

cein

apr

ogra

m,o

rif

you

just

wan

tto

keep

the

rege

xps

sepa

rate

dso

meh

ow,y

oush

ould

crea

tea

patte

rnob

ject

,and

refe

rto

itla

terw

hen

sear

chin

g/re

plac

ing.

Tocr

eate

apa

ttern

obje

ct,u

seth

eco

mpi

lefu

nctio

n.

import

re

foo

=re.compile(r'foo(.{,5})bar',

re.I+re.S)

The

first

argu

men

tis

the

patte

rn,w

hich

mat

ches

the

stri

ng"f

oo",

follo

wed

byup

to5

ofan

ych

arac

ter,

then

the

stri

ng"b

ar",

stor

ing

the

mid

dle

char

acte

rsto

agr

oup,

whi

chw

illbe

disc

usse

dla

ter.

The

seco

nd,o

ptio

nal,

argu

men

tis

the

flag

orfla

gsto

mod

ify

the

rege

xp's

beha

vior

.The

flags

them

selv

esar

esi

mpl

y

Page 244: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

vari

able

sre

ferr

ing

toan

inte

ger

used

byth

ere

gula

rex

pres

sion

engi

ne.

Inot

herl

angu

ages

,the

sew

ould

beco

nsta

nts,

butP

ytho

ndo

esno

thav

eco

nsta

nts.

Som

eof

the

regu

lar

expr

essi

onfu

nctio

nsdo

not

supp

ort

addi

ngfla

gsas

apa

ram

eter

whe

nde

finin

gth

epa

ttern

dire

ctly

inth

efu

nctio

n,if

you

need

any

ofth

efla

gs,i

tis

best

tous

eth

eco

mpi

lefu

nctio

nto

crea

tea

patte

rnob

ject

.

The

rpr

eced

ing

the

expr

essi

onst

ring

indi

cate

sth

atit

shou

ldbe

trea

ted

asa

raw

stri

ng.

Thi

ssh

ould

norm

ally

beus

edw

hen

wri

ting

rege

xps,

soth

atba

cksl

ashe

sar

ein

terp

rete

dlit

eral

lyra

ther

than

havi

ngto

bees

cape

d.

The

diff

eren

tflag

sar

e:

Abb

revi

atio

nFu

llna

me

Des

crip

tion

re.I

re.IGNORECASE

Mak

esth

ere

gexp

case

-ins

ensi

tive3

3http://en.wikipedia.org/wiki/case%20sensitivity

Page 245: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Abb

revi

atio

nFu

llna

me

Des

crip

tion

re.L

re.LOCALE

Mak

esth

ebe

havi

orof

som

esp

ecia

lse-

quen

ces

(\w,\W,

\b,\B,\s,\S

)de

pend

ento

nth

ecu

r-re

ntlo

cale

4

re.M

re.MULTILINE

Mak

esth

and$

char

acte

rsm

atch

atth

ebe

ginn

ing

and

end

ofea

chlin

e,ra

ther

than

just

the

begi

n-ni

ngan

den

dof

the

stri

ng

4http://en.wikipedia.org/wiki/locale

Page 246: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Abb

revi

atio

nFu

llna

me

Des

crip

tion

re.S

re.DOTALL

Mak

esth

e.

char

-ac

term

atch

ever

ych

arac

teri

nclu

ding

new

lines

.re.U

re.UNICODE

Mak

es\w,\W,

\b,\B,\d,\D,

\s,\S

depe

nden

ton

Uni

code

char

acte

rpr

oper

ties

Page 247: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Abb

revi

atio

nFu

llna

me

Des

crip

tion

re.X

re.VERBOSE

Igno

res

whi

tesp

ace

exce

ptw

hen

ina

char

acte

rcla

ssor

prec

eded

byan

non-

esca

ped

back

slas

h,an

dig

nore

s#

(exc

ept

whe

nin

ach

arac

ter

clas

sor

prec

eded

byan

non-

esca

ped

back

-sl

ash)

and

ever

ythi

ngaf

teri

tto

the

end

ofa

line,

soit

can

beus

edas

aco

mm

ent.

Thi

sal

low

sfo

rcle

aner

-lo

okin

gre

gexp

s.

Page 248: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

21.2

Mat

chin

gan

dse

arch

ing

One

ofth

em

ostc

omm

onus

esfo

rreg

ular

expr

essi

ons

isex

trac

ting

apa

rtof

ast

ring

orte

stin

gfo

rthe

exis

tenc

eof

apa

ttern

ina

stri

ng.P

ytho

nof

fers

seve

ral

func

tions

todo

this

.

The

mat

chan

dse

arch

func

tions

dom

ostly

the

sam

eth

ing,

exce

ptth

atth

em

atch

func

tion

will

only

retu

rna

resu

ltif

the

patte

rnm

atch

esat

the

begi

nnin

gof

the

stri

ngbe

ing

sear

ched

,whi

lese

arch

will

find

am

atch

anyw

here

inth

est

ring

.

>>>

import

re

>>>

foo

=re.compile(r'foo(.{,5})bar',

re.I+re.S)

>>>

st1

='Foo,

Bar,

Baz'

>>>

st2

='2.

foo

is

bar'

>>>

search1

=foo.search(st1)

>>>

search2

=foo.search(st2)

>>>

match1

=foo.match(st1)

>>>

match2

=foo.match(st2)

Page 249: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Inth

isex

ampl

e,m

atch

2w

illbe

None

,bec

ause

the

stri

ngst2

does

nots

tart

with

the

give

npa

ttern

.The

othe

r3re

sults

will

beM

atch

obje

cts

(see

belo

w).

You

can

also

mat

chan

dse

arch

with

outc

ompi

ling

are

gexp

:

>>>

search3

=re.search('oo.*ba',

st1,

re.I)

Her

ew

eus

eth

ese

arch

func

tion

ofth

ere

mod

ule,

rath

erth

anof

the

patte

rnob

ject

.For

mos

tcas

es,i

tsbe

stto

com

pile

the

expr

essi

onfir

st.N

otal

loft

here

mod

ule

func

tions

supp

ortt

hefla

gsar

gum

enta

ndif

the

expr

essi

onis

used

mor

eth

anon

ce,c

ompi

ling

first

ism

ore

effic

ient

and

lead

sto

clea

nerl

ooki

ngco

de.

The

com

pile

dpa

ttern

obje

ctfu

nctio

nsal

soha

vepa

ram

eter

sfo

rsta

rtin

gan

den

ding

the

sear

ch,

tose

arch

ina

subs

trin

gof

the

give

nst

ring

.In

the

first

exam

ple

inth

isse

ctio

n,match2

retu

rns

nore

sult

beca

use

the

patte

rndo

esno

tsta

rtat

the

begi

nnin

gof

the

stri

ng,b

utif

we

do:

>>>

match3

=foo.match(st2,

3)

Page 250: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

itw

orks

,be

caus

ew

ete

llit

tost

art

sear

chin

gat

char

acte

rnu

mbe

r3

inth

est

ring

.

Wha

tifw

ew

antt

ose

arch

form

ultip

lein

stan

ces

ofth

epa

ttern

?Th

enw

eha

vetw

oop

tions

.W

eca

nus

eth

est

arta

nden

dpo

sitio

npa

ram

eter

sof

the

sear

chan

dm

atch

func

tion

ina

loop

,get

ting

the

posi

tion

tost

arta

tfro

mth

epr

evio

usm

atch

obje

ct(s

eebe

low

)orw

eca

nus

eth

efin

dall

and

findi

terf

unct

ions

.The

finda

llfu

nctio

nre

turn

sa

listo

fmat

chin

gst

ring

s,us

eful

fors

impl

ese

arch

ing.

For

anyt

hing

slig

htly

com

plex

,th

efin

dite

rfu

nctio

nsh

ould

beus

ed.

Thi

sre

turn

san

itera

toro

bjec

t,th

atw

hen

used

ina

loop

,yie

lds

Mat

chob

ject

s.Fo

rex

ampl

e:

>>>

str3

='foo,

Bar

Foo.

BAR

FoO:

bar'

>>>

foo.findall(str3)

[',

',

'.

',

':

']

>>>

formatch

in

foo.finditer(str3):

...

match.group(1)

...

',

''.

'':

'

Page 251: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Ifyo

u're

goin

gto

beite

ratin

gov

erth

ere

sults

ofth

ese

arch

,usi

ngth

efin

dite

rfu

nctio

nis

alm

osta

lway

sa

bette

rcho

ice.

21.2

.1M

atch

obje

cts

Mat

chob

ject

sar

ere

turn

edby

the

sear

chan

dm

atch

func

tions

,and

incl

ude

info

rmat

ion

abou

tthe

patte

rnm

atch

.

The

grou

pfu

nctio

nre

turn

sa

strin

gco

rres

pond

ing

toa

capt

ure

grou

p(p

arto

fare

gexp

wra

pped

in()

)oft

heex

pres

sion

,ori

fno

grou

pnu

mbe

ris

give

n,th

een

tire

mat

ch.U

sing

thesearch1

vari

able

we

defin

edab

ove:

>>>

search1.group()

'Foo,

Bar'

>>>

search1.group(1)

',

'

Page 252: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Cap

ture

grou

psca

nal

sobe

give

nst

ring

nam

esus

ing

asp

ecia

lsyn

tax

and

refe

rred

toby

matchobj.group('name')

.For

sim

ple

expr

essi

ons

this

isun

nece

ssar

y,bu

tfor

mor

eco

mpl

exex

pres

sion

sit

can

beve

ryus

eful

.

You

can

also

gett

hepo

sitio

nof

am

atch

ora

grou

pin

ast

ring

,usi

ngth

est

art

and

end

func

tions

:

>>>

search1.start()

0 >>>

search1.end()

8 >>>

search1.start(1)

3 >>>

search1.end(1)

5 Thi

sre

turn

sth

est

arta

nden

dlo

catio

nsof

the

entir

em

atch

,and

the

star

tand

end

ofth

efir

st(a

ndin

this

case

only

)cap

ture

grou

p,re

spec

tivel

y.

Page 253: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

21.3

Rep

laci

ng

Ano

ther

use

forr

egul

arex

pres

sion

sis

repl

acin

gte

xtin

ast

ring

.To

doth

isin

Pyth

on,u

seth

esu

bfu

nctio

n.

sub

take

sup

to3

argu

men

ts:

The

text

tore

plac

ew

ith,t

hete

xtto

repl

ace

in,

and,

optio

nally

,the

max

imum

num

ber

ofsu

bstit

utio

nsto

mak

e.U

nlik

eth

em

atch

ing

and

sear

chin

gfu

nctio

ns,s

ubre

turn

sa

stri

ng,c

onsi

stin

gof

the

give

nte

xtw

ithth

esu

bstit

utio

n(s)

mad

e.

>>>

import

re

>>>

mystring

='This

string

has

aq

in

it'

>>>

pattern

=re.compile(r'(a[n]?

)(\w)

')

>>>

newstring

=pattern.sub(r"\1'\2'

",

mystring)

>>>

newstring

"This

string

has

a'q'

in

it"

This

take

san

ysi

ngle

alph

anum

eric

char

acte

r(\w

inre

gula

rexp

ress

ion

synt

ax)

prec

eded

by"a

"or

"an"

and

wra

psin

insi

ngle

quot

es.T

he\1

and\2

inth

e

Page 254: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

repl

acem

ents

tring

are

back

refe

renc

esto

the

2ca

ptur

egr

oups

inth

eex

pres

sion

;th

ese

wou

ldbe

grou

p(1)

and

grou

p(2)

ona

Mat

chob

ject

from

ase

arch

.

The

subn

func

tion

issi

mila

rto

sub,

exce

ptit

retu

rns

atu

ple,

cons

istin

gof

the

resu

ltst

ring

and

the

num

bero

frep

lace

men

tsm

ade.

Usi

ngth

est

ring

and

expr

essi

onfr

ombe

fore

:

>>>

subresult

=pattern.subn(r"\1'\2'

",

mystring)

>>>

subresult

("This

string

has

a'q'

in

it",

1)

21.4

Oth

erfu

nctio

ns

The

rem

odul

eha

sa

few

othe

rfun

ctio

nsin

addi

tion

toth

ose

disc

usse

dab

ove.

The

split

func

tion

split

sa

stri

ngba

sed

ona

give

nre

gula

rexp

ress

ion:

>>>

import

re

Page 255: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

mystring

='1.

First

part

2.

Second

part

3.

Third

part'

>>>

re.split(r'\d\.',

mystring)

['',

'First

part

',

'Second

part

',

'Third

part']

The

esca

pefu

nctio

nes

cape

sal

lnon

-alp

hanu

mer

icch

arac

ters

ina

stri

ng.T

his

isus

eful

ifyo

une

edto

take

anun

know

nst

ring

that

may

cont

ain

rege

xpm

etac

hara

cter

slik

e(

and.

and

crea

tea

regu

lare

xpre

ssio

nfr

omit.

>>>

re.escape(r'This

text

(and

this)

must

be

escaped

with

a"\"

to

use

in

aregexp.')

'This\\

text\\

\\(and\\

this\\)\\

must\\

be\\

escaped\\

with\\

a\\

\\"\\\\\\"\\

to\\

use\\

in\\

a\\

regexp\\.'

21.5

Ext

erna

llin

ks

•Py

thonre

docu

men

tatio

n5-F

ulld

ocum

enta

tion

fort

here

mod

ule,

incl

udin

gpa

ttern

obje

cts

and

mat

chob

ject

s

5http://docs.python.org/library/re.html

Page 256: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

fr:P

rogr

amm

atio

nPy

thon

/Reg

ex6

6http://fr.wikibooks.org/wiki/Programmation%20Python%

2FRegex

Page 257: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 258: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22G

UIP

rogr

amm

ing

The

rear

eva

riou

sG

UIt

oolk

itsto

star

twith

.

22.1

Tki

nter

Tkin

ter,

aPy

thon

wra

pper

for

Tcl/T

k1 ,com

esbu

ndle

dw

ithPy

thon

(atl

east

onW

in32

plat

form

thou

ghit

can

bein

stal

led

onU

nix/

Lin

uxan

dM

acm

achi

nes)

and

prov

ides

acr

oss-

plat

form

GU

I.It

isa

rela

tivel

ysi

mpl

eto

lear

nye

tpow

erfu

l

1http://en.wikibooks.org/wiki/Programming%3ATcl%20

251

Page 259: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

tool

kitt

hatp

rovi

des

wha

tapp

ears

tobe

am

odes

tset

ofw

idge

ts.

How

ever

,be

caus

eth

eT

kint

erw

idge

tsar

eex

tens

ible

,man

yco

mpo

und

wid

gets

can

becr

eate

dra

ther

easi

ly(e

.g.c

ombo

-box

,scr

olle

dpa

nes)

.Bec

ause

ofits

mat

urity

and

exte

nsiv

edo

cum

enta

tion

Tki

nter

has

been

desi

gnat

edas

the

defa

cto

GU

Ifo

rPyt

hon.

Tocr

eate

ave

rysi

mpl

eT

kint

erw

indo

wfr

ame

one

only

need

sth

efo

llow

ing

lines

ofco

de:

import

Tkinter

root

=Tkinter.Tk()

root.mainloop()

From

anob

ject

-ori

ente

dpe

rspe

ctiv

eon

eca

ndo

the

follo

win

g:

import

Tkinter

class

App:

def__init__(self,

master):

Page 260: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

button

=Tkinter.Button(master,

text="I'm

aButton.")

button.pack()

if

__name__==

'__main__':

root

=Tkinter.Tk()

app

=App(root)

root.mainloop()

Tole

arn

mor

eab

outT

kint

ervi

sitt

hefo

llow

ing

links

:

•ht

tp://

ww

w.a

stro

.was

hing

ton.

edu/

user

s/ro

wen

/Tki

nter

Sum

mar

y.ht

ml2

<-A

sum

mar

y

http

://in

foho

st.n

mt.e

du/tc

c/he

lp/la

ng/p

ytho

n/tk

inte

r.htm

l3<-

Atu

tori

al

•ht

tp://

ww

w.p

ytho

nwar

e.co

m/li

brar

y/tk

inte

r/in

trod

uctio

n/4

<-A

refe

renc

e

2http://www.astro.washington.edu/users/rowen/TkinterSummary.

html

3http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html

4http://www.pythonware.com/library/tkinter/introduction/

Page 261: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22.2

PyG

TK

See

also

book

PyG

TKFo

rG

UIP

rogr

amm

ing5

PyG

TK

6pr

ovid

esa

conv

enie

ntw

rapp

erfo

rth

eG

TK

+7lib

rary

for

use

inPy

thon

prog

ram

s,ta

king

care

ofm

any

ofth

ebo

ring

deta

ilssu

chas

man

agin

gm

emor

yan

dty

peca

stin

g.T

heba

reG

TK

+to

olki

trun

son

Lin

ux,W

indo

ws,

and

Mac

OS

X(p

orti

npr

ogre

ss),

butt

hem

ore

exte

nsiv

efe

atur

es—

whe

nco

mbi

ned

with

PyO

RB

itan

dgn

ome-

pyth

on—

requ

ire

aG

NO

ME

8in

stal

l,an

dca

nbe

used

tow

rite

full

feat

ured

GN

OM

Eap

plic

atio

ns.

Hom

ePa

ge9

5http://en.wikibooks.org/wiki/PyGTK%20For%20GUI%

20Programming

6http://www.pygtk.org/

7http://www.gtk.org

8http://www.gnome.org

9http://www.pygtk.org/

Page 262: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22.3

PyQ

t

PyQ

tis

aw

rapp

erar

ound

the

cros

s-pl

atfo

rmQ

tC++

tool

kit10

.Ith

asm

any

wid

gets

and

supp

ort

clas

ses11

supp

ortin

gSQ

L,O

penG

L,S

VG

,XM

L,a

ndad

vanc

edgr

aphi

csca

pabi

litie

s.A

PyQ

thel

low

orld

exam

ple:

from

PyQt4.QtCore

import

*from

PyQt4.QtGui

import

*

class

App(QApplication):

def__init__(self,

argv):

super(App,

self).__init__(argv)

self.msg

=QLabel("Hello,

World!")

self.msg.show()

if

__name__==

"__main__":

import

sys

10http://www.trolltech.com/products/qt

11http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.

html

Page 263: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

app

=App(sys.argv)

sys.exit(app.exec_)

PyQ

t12is

ase

tofb

indi

ngs

fort

hecr

oss-

plat

form

Qt13

appl

icat

ion

fram

ewor

k.Py

Qtv

4su

ppor

tsQ

t4an

dPy

Qtv

3su

ppor

tsQ

t3an

dea

rlie

r.

22.4

wxP

ytho

n

Bin

ding

sfo

rthe

cros

spl

atfo

rmto

olki

tw

xWid

gets

14.W

xWid

gets

isav

aila

ble

onW

indo

ws,

Mac

into

sh,a

ndU

nix/

Lin

ux.

import

wx

class

test(wx.App):

def__init__(self):

12http://www.riverbankcomputing.co.uk/pyqt/

13http://en.wikibooks.org/wiki/Qt

14http://www.wxwidgets.org/

Page 264: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

wx.App.__init__(self,

redirect=False)

defOnInit(self):

frame

=wx.Frame(None,

-1,

"Test",

pos=(50,50),

size=(100,40),

style=wx.DEFAULT_FRAME_STYLE)

button

=wx.Button(frame,

-1,

"Hello

World!",

(20,

20))

self.frame

=frame

self.frame.Show()

returnTrue

if

__name__==

'__main__':

app

=test()

app.MainLoop()

•w

xPyt

hon15

15http://wxpython.org/

Page 265: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22.5

Dab

o

Dab

ois

afu

ll3-

tiera

pplic

atio

nfr

amew

ork.

Its

UIl

ayer

wra

psw

xPyt

hon,

and

grea

tlysi

mpl

ifies

the

synt

ax.

import

dabo

dabo.ui.loadUI("wx")

class

TestForm(dabo.ui.dForm):

defafterInit(self):

self.Caption

="Test"

self.Position

=(50,

50)

self.Size

=(100,

40)

self.btn

=dabo.ui.dButton(self,

Caption="Hello

World",

OnHit=self.onButtonClick)

self.Sizer.append(self.btn,

halign="center",

border=20)

defonButtonClick(self,

evt):

dabo.ui.info("Hello

World!")

if

__name__==

'__main__':

app

=dabo.ui.dApp()

Page 266: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

app.MainFormClass

=TestForm

app.start()

•D

abo16

22.6

pyFl

tk

pyFl

tk17

isa

Pyth

onw

rapp

erfo

rth

eFL

TK

18,a

light

wei

ghtc

ross

-pla

tfor

mG

UIt

oolk

it.It

isve

rysi

mpl

eto

lear

nan

dal

low

sfo

rcom

pact

user

inte

rfac

es.

The

"Hel

loW

orld

"ex

ampl

ein

pyFl

tklo

oks

like:

from

fltk

import

*

window

=Fl_Window(100,

100,

200,

90)

16http://dabodev.com/

17http://pyfltk.sourceforge.net/

18http://www.fltk.org/

Page 267: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

button

=Fl_Button(9,20,180,50)

button.label("Hello

World")

window.end()

window.show()

Fl.run()

22.7

Oth

erTo

olki

ts

•Py

KD

E19

-Par

toft

hekd

ebin

ding

spa

ckag

e,it

prov

ides

apy

thon

wra

pper

fort

heK

DE

libra

ries

.•

PyX

PCO

M20

prov

ides

aw

rapp

erar

ound

the

Moz

illa

XPC

OM

21co

mpo

nent

arch

itect

ure,

ther

eby

enab

ling

the

use

ofst

anda

lone

XU

L22

appl

icat

ions

inPy

thon

.T

heX

UL

tool

kith

astr

aditi

onal

lybe

enw

rapp

edup

inva

riou

s

19http://www.riverbankcomputing.co.uk/pykde/index.php

20http://developer.mozilla.org/en/docs/PyXPCOM

21http://developer.mozilla.org/en/docs/XPCOM

22http://developer.mozilla.org/en/docs/XUL

Page 268: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

othe

rpar

tsof

XPC

OM

,but

with

the

adve

ntof

libxu

land

XU

LRun

ner23

this

shou

ldbe

com

em

ore

feas

ible

.

pt:P

ytho

n/Pr

ogra

maç

ãoco

mG

UI24

23http://developer.mozilla.org/en/docs/XULRunner

24http://pt.wikibooks.org/wiki/Python%2FPrograma%E7%E3o%

20com%20GUI

Page 269: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 270: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

23G

ame

Prog

ram

min

gin

Pyth

on

23.1

3DG

ame

Prog

ram

min

g

23.1

.13D

Gam

eE

ngin

ew

itha

Pyth

onbi

ndin

g

•Ir

rlic

htE

ngin

ehttp

://ir

rlic

ht.s

ourc

efor

ge.n

et/1

(Pyt

hon

bind

ing

web

site

:ht

tp://

pypi

.pyt

hon.

org/

pypi

/pyi

rrlic

ht2

)

1http://irrlicht.sourceforge.net/

2http://pypi.python.org/pypi/pyirrlicht

263

Page 271: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•O

gre

Eng

ine

http

://w

ww

.ogr

e3d.

org/

3(P

ytho

nbi

ndin

gw

ebsi

te:

http

://w

ww

.pyt

hon-

ogre

.org

/4)

Bot

har

eve

rygo

odfr

eeop

enso

urce

C++

3Dga

me

Eng

ine

with

aPy

thon

bind

ing.

•C

ryst

alSp

ace5

isa

free

cros

s-pl

atfo

rmso

ftwar

ede

velo

pmen

tkit

forr

eal-t

ime

3Dgr

aphi

cs,w

ithpa

rtic

ular

focu

son

gam

es.

Cry

stal

Spac

eis

acce

ssib

lefr

omPy

thon

intw

ow

ays:

(1)

asa

Cry

stal

Spac

epl

ugin

mod

ule

inw

hich

C++

code

can

call

upon

Pyth

onco

de,a

ndin

whi

chPy

thon

code

can

call

upon

Cry

stal

Spac

e;(2

)as

apu

rePy

thon

mod

ule

nam

ed‘c

spac

e’w

hich

one

can

‘im

port

’fro

mw

ithin

Pyth

onpr

ogra

ms.

Tous

eth

efir

stop

tion,

load

the

‘csp

ytho

n’pl

ugin

asyo

uw

ould

load

any

othe

rC

ryst

alSp

ace

plug

in,a

ndin

tera

ctw

ithit

via

the

SCF

‘iSc

ript

’int

erfa

ce.T

hese

cond

appr

oach

allo

ws

3http://www.ogre3d.org/

4http://www.python-ogre.org/

5http://www.crystalspace3d.org

Page 272: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

you

tow

rite

Cry

stal

Spac

eap

plic

atio

nsen

tirel

yin

Pyth

on,w

ithou

tany

C++

codi

ng.

CS

Wik

i6

23.1

.23D

Gam

eE

ngin

esw

ritt

enfo

rPy

thon

Eng

ines

desi

gned

forP

ytho

nfr

omsc

ratc

h.

•B

lend

er7

isan

impr

essi

ve3D

tool

with

afu

llyin

tegr

ated

3Dgr

aphi

cscr

eatio

nsu

iteal

low

ing

mod

elin

g,an

imat

ion,

rend

erin

g,po

st-p

rodu

ctio

n,re

al-t

ime

inte

ract

ive

3Dan

dga

me

crea

tion

and

play

back

with

cros

s-pl

atfo

rmco

mpa

ti-bi

lity.

The

3Dga

me

engi

neus

esan

embe

dded

pyth

onin

terp

rete

rto

mak

e3D

gam

es.

•Py

Soy8

isa

3dcl

oud

gam

een

gine

forP

ytho

n3.

Itw

asde

sign

edfo

rrap

idde

velo

pmen

twith

anin

tuiti

veA

PIth

atge

tsne

wga

me

deve

lope

rsst

arte

d

6http://en.wikipedia.org/wiki/Crystal_Space

7http://www.blender.org/

8http://www.pysoy.org/

Page 273: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

quic

kly.

The

clou

dga

min

g9de

sign

allo

ws

PySo

yga

mes

tobe

play

edon

ase

rver

with

outd

ownl

oadi

ngth

em,g

reat

lyre

duci

ngth

eco

mpl

exity

ofga

me

dist

ribu

tion.

XM

PP10

acco

unts

(suc

has

Jabb

eror

GM

ail)

can

beus

edfo

ron

line

gam

ing

iden

titie

s,ch

at,a

ndin

itiat

ing

conn

ectio

nsto

gam

ese

rver

s.Py

Soy

isre

leas

edun

dert

heG

NU

AG

PLlic

ense

11.

•So

ya12

isa

3Dga

me

engi

new

ithan

easy

toun

ders

tand

desi

gn.I

tsw

ritte

nin

the

Pyre

x13pr

ogra

mm

ing

lang

uage

and

uses

Cal

3dfo

ran

imat

ion

and

OD

E14

forp

hysi

cs.S

oya

isav

aila

ble

unde

rthe

GN

UG

PLlic

ense

15.

•Pa

nda3

D16

isa

3Dga

me

engi

ne.I

t'sa

libra

ryw

ritte

nin

C++

with

Pyth

onbi

ndin

gs.P

anda

3Dis

desi

gned

inor

dert

osu

ppor

tash

ortl

earn

ing

curv

ean

d

9http://en.wikipedia.org/wiki/Cloud_gaming

10http://en.wikipedia.org/wiki/XMPP

11http://en.wikipedia.org/wiki/GNU_AGPL

12http://www.soya3d.org/

13http://en.wikipedia.org/wiki/Pyrex%20programming%

20language

14http://en.wikipedia.org/wiki/Open%20Dynamics%20Engine

15http://en.wikipedia.org/wiki/GNU_GPL

16http://www.panda3d.org/

Page 274: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

rapi

dde

velo

pmen

t.Th

isso

ftwar

eis

avai

labl

efo

rfre

edo

wnl

oad

with

sour

ceco

deun

der

the

BSD

Lic

ense

.T

hede

velo

pmen

twas

star

ted

by[D

isne

y].

Now

ther

ear

em

any

proj

ects

mad

ew

ithPa

nda3

D,s

uch

asD

isne

y's

Pira

te's

ofth

eC

arib

bean

Onl

ine17

,To

onTo

wn18

,B

uild

ing

Vir

tual

Wor

ld19

,Sc

hell

Gam

es20

and

man

yot

hers

.Pan

da3D

supp

orts

seve

ralf

eatu

res:

Proc

edur

alG

eom

etry

,Ani

mat

edTe

xtur

e,R

ende

rto

text

ure,

Trac

km

otio

n,fo

g,pa

rtic

lesy

stem

,and

man

yot

hers

.•

Cry

stal

Spac

e21Is

a3D

gam

een

gine

,w

itha

Pyth

onbi

ndin

gs,

nam

ed*

PyC

ryst

al22

,vie

wW

ikip

edia

page

of*

Cry

stal

Spac

e23.

17http://disney.go.com/pirates/online/

18http://www.toontown.com/

19http://www.etc.cmu.edu/bvw

20http://www.schellgames.com

21http://www.crystalspace3d.org/

22http://www.crystalspace3d.org/main/PyCrystal

23http://en.wikipedia.org/wiki/Crystalspace

Page 275: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

23.2

2DG

ame

Prog

ram

min

g

•Py

gam

e24is

acr

oss

plat

form

Pyth

onlib

rary

whi

chw

raps

SDL25

.Itp

rovi

des

man

yfe

atur

eslik

eSp

rite

grou

psan

dso

und/

imag

elo

adin

gan

dea

sych

angi

ngof

anob

ject

spo

sitio

n.It

also

prov

ides

the

prog

ram

mer

acce

ssto

key

and

mou

seev

ents

.•

Phil'

sPy

gam

eU

tiliti

es(P

GU

)26is

aco

llect

ion

ofto

ols

and

libra

ries

that

enha

nce

Pyga

me.

Tool

sin

clud

ea

tile

edito

ran

da

leve

ledi

tor27

(tile

,iso

-m

etri

c,he

xago

nal)

.GU

Ienh

ance

men

tsin

clud

efu

llfe

atur

edG

UI,

HT

ML

rend

erin

g,do

cum

ent

layo

ut,

and

text

rend

erin

g.T

helib

rari

esin

clud

ea

spri

tean

dtil

een

gine

28(t

ile,i

som

etri

c,he

xago

nal)

,ast

ate

engi

ne,a

timer

,an

da

high

scor

esy

stem

.(B

eta

with

last

upda

teM

arch

,20

07.

API

sto

bede

prec

ated

and

isom

etri

can

dhe

xago

nals

uppo

rtis

curr

ently

Alp

haan

d

24http://en.wikipedia.org/wiki/Pygame

25http://en.wikipedia.org/wiki/SDL

26http://www.imitationpickles.org/pgu/wiki/index

27http://en.wikipedia.org/wiki/Level_editor

28http://en.wikipedia.org/wiki/Tile_engine

Page 276: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

subj

ectt

och

ange

.)[U

pdat

e27

/02/

08A

utho

rin

dica

tes

heis

notc

urre

ntly

activ

ely

deve

lopi

ngth

islib

rary

and

anyo

neth

atis

will

ing

tode

velo

pth

eir

own

scro

lling

isom

etri

clib

rary

offe

ring

can

use

the

exis

ting

code

inPG

Uto

gett

hem

star

ted.

]•

Pygl

et29

isa

cros

s-pl

atfo

rmw

indo

win

gan

dm

ultim

edia

libra

ryfo

rPyt

hon

with

noex

tern

alde

pend

enci

esor

inst

alla

tion

requ

irem

ents

.Pyg

letp

rovi

des

anob

ject

-ori

ente

dpr

ogra

mm

ing

inte

rfac

efo

rdev

elop

ing

gam

esan

dot

her

visu

ally

-ric

hap

plic

atio

nsfo

rWin

dow

s30,M

acO

SX

31an

dL

inux

32.P

ygle

tal

low

spr

ogra

ms

toop

enm

ultip

lew

indo

ws

onm

ultip

lesc

reen

s,dr

awin

thos

ew

indo

wsw

ithO

penG

L,an

dpl

ayba

ckau

dio

and

vide

oin

mos

tfor

mat

s.U

nlik

esi

mila

rlib

rarie

sav

aila

ble,

pygl

etha

sno

exte

rnal

depe

nden

cies

(suc

has

SDL

)and

isw

ritte

nen

tirel

yin

Pyth

on.P

ygle

tis

avai

labl

eun

dera

BSD

-St

yle

licen

se33

.

29http://www.pyglet.org/

30http://en.wikipedia.org/wiki/Windows

31http://en.wikipedia.org/wiki/Mac_OS_X

32http://en.wikipedia.org/wiki/Linux

33http://en.wikipedia.org/wiki/BSD_licenses

Page 277: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•K

ivy34

Kiv

yis

alib

rary

ford

evel

opin

gm

ulti-

touc

hap

plic

atio

ns.I

tis

com

-pl

etel

ycr

oss-

plat

form

(Lin

ux/O

SX/W

in&

And

roid

with

Ope

nGL

ES2

).It

com

esw

ithna

tive

supp

ortf

orm

any

mul

ti-to

uch

inpu

tdev

ices

,agr

owin

glib

rary

ofm

ulti-

touc

haw

are

wid

gets

and

hard

war

eac

cele

rate

dO

penG

Ldr

awin

g.K

ivy

isde

sign

edto

lety

oufo

cus

onbu

ildin

gcu

stom

and

high

lyin

tera

ctiv

eap

plic

atio

nsas

quic

kly

and

easi

lyas

poss

ible

.•

Rab

byt35

Afa

stSp

rite

36lib

rary

for

Pyth

onw

ithga

me

deve

lopm

ent

inm

ind.

With

Rab

bytA

nim

s,ev

enol

dgr

aphi

csca

rds

can

prod

uce

very

fast

anim

atio

nsof

2,40

0or

mor

esp

rite

sha

ndlin

gpo

sitio

n,ro

tatio

n,sc

alin

g,an

dco

lors

imul

tane

ousl

y.

34http://kivy.org/

35http://arcticpaint.com/projects/rabbyt/

36http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%

29

Page 278: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

23.3

See

Als

o

•10

Les

sons

Lea

rned

37-

How

ToB

uild

aG

ame

InA

Wee

kFr

omSc

ratc

hW

ithN

oB

udge

t

37http://www.gamedev.net/reference/articles/article2259.asp

Page 279: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 280: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

24So

cket

s

24.1

HT

TP

Clie

nt

Mak

ea

very

sim

ple

HT

TP

clie

nt

import

socket

s=

socket.socket()

s.connect(('localhost',

80))

s.send('GET

/HTTP/1.1\nHost:localhost\n\n')

s.recv(40000)

#receive

40000

bytes

273

Page 281: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

24.2

NT

P/So

cket

s

Con

nect

ing

toan

dre

adin

gan

NT

Ptim

ese

rver

,ret

urni

ngth

etim

eas

follo

ws

ntpps

picoseconds

portion

of

time

ntps

seconds

portion

of

time

ntpms

milliseconds

portion

of

time

ntpt

64-bit

ntp

time,

seconds

in

upper

32-bits,

picoseconds

in

lower

32-bits

Page 282: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

25Fi

les

25.1

File

I/O

Rea

den

tire

file:

inputFileText

=open("testit.txt",

"r").read()

print(inputFileText)

Inth

isca

seth

e"r

"pa

ram

eter

mea

nsth

efil

ew

illbe

open

edin

read

-onl

ym

ode.

Rea

dce

rtai

nam

ount

ofby

tes

from

afil

e:

275

Page 283: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

inputFileText

=open("testit.txt",

"r").read(123)

print(inputFileText)

Whe

nop

enin

ga

file,

one

star

tsre

adin

gat

the

begi

nnin

gof

the

file,

ifon

ew

ould

wan

tmor

era

ndom

acce

ssto

the

file,

itis

poss

ible

tous

eseek()

toch

ange

the

curr

entp

ositi

onin

afil

ean

dtell()

toge

tto

know

the

curr

ent

posi

tion

inth

efil

e.T

his

isill

ustr

ated

inth

efo

llow

ing

exam

ple:

>>>

f=open("/proc/cpuinfo","r")

>>>

f.tell()

0L>>>

f.read(10)

'processor\t'

>>>

f.read(10)

':

0\nvendor'

>>>

f.tell()

20L

>>>

f.seek(10)

>>>

f.tell()

10L

>>>

f.read(10)

':

0\nvendor'

Page 284: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

>>>

f.close()

>>>

f<closed

file

'/proc/cpuinfo',

mode

'r'

at

0xb7d79770>

Her

ea

file

isop

ened

,tw

ice

ten

byte

sar

ere

ad,tell()

show

sth

atth

ecu

rren

tof

fset

isat

posi

tion

20,n

owseek()

isus

edto

goba

ckto

posi

tion

10(t

hesa

me

posi

tion

whe

reth

ese

cond

read

was

star

ted)

and

ten

byte

sar

ere

adan

dpr

inte

dag

ain.

And

whe

nno

mor

eop

erat

ions

ona

file

are

need

edth

eclose()

func

tion

isus

edto

clos

eth

efil

ew

eop

ened

.

Rea

don

elin

eat

atim

e:

for

line

in

open("testit.txt",

"r"):

printline

Inth

isca

sereadlines()

will

retu

rnan

arra

yco

ntai

ning

the

indi

vidu

allin

esof

the

file

asar

ray

entr

ies.

Rea

ding

asi

ngle

line

can

bedo

neus

ing

thereadline()

func

tion

whi

chre

turn

sth

ecu

rren

tlin

eas

ast

ring

.T

his

exam

ple

will

outp

utan

addi

tiona

lne

wlin

ebe

twee

nth

ein

divi

dual

lines

of

Page 285: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

the

file,

this

isbe

caus

eon

eis

read

from

the

file

and

prin

tint

rodu

ces

anot

her

new

line.

Wri

teto

afil

ere

quir

esth

ese

cond

para

met

erofopen()

tobe

"w",

this

will

over

wri

teth

eex

istin

gco

nten

tsof

the

file

ifit

alre

ady

exis

tsw

hen

open

ing

the

file:

outputFileText

="Here's

some

text

to

save

in

afile"

open("testit.txt",

"w").write(outputFileText)

App

end

toa

file

requ

ires

the

seco

ndpa

ram

eter

ofopen()

tobe

"a"

(fro

map

pend

):

outputFileText

="Here's

some

text

to

add

to

the

existing

file."

open("testit.txt",

"a").write(outputFileText)

Not

eth

atth

isdo

esno

tadd

alin

ebr

eak

betw

een

the

exis

ting

file

cont

enta

ndth

est

ring

tobe

adde

d.

Page 286: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

As

anot

her

impo

rtan

tex

ampl

e,if

you

wan

tto

read

alis

tof

num

bers

ina

file(

both

indi

ffer

entl

ines

,and

sam

elin

es),

and

putt

henu

mbe

rsin

one

line

near

each

othe

r,se

para

teth

enu

mbe

rsin

diff

eren

tlin

es,i

na

list,

one

fast

way

wou

ldbe

:

f=

open("C:\Documents

and

Settings\Pardis

Rayan\Desktop\SCC\SCC.txt","r")

g=

[[int(i)for

iin

line.split()

]forline

in

f]

25.2

Test

ing

File

s

Det

erm

ine

whe

ther

path

exis

ts:

import

os

os.path.exists('<path

string>')

Page 287: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Whe

nw

orki

ngon

syst

ems

such

asM

icro

soft

Win

dow

s™,t

hedi

rect

ory

sepa

-ra

tors

will

confl

ictw

ithth

epa

thst

ring

.To

geta

roun

dth

is,d

oth

efo

llow

ing:

import

os

os.path.exists('C:\\windows\\example\\path')

Abe

tterw

ayho

wev

eris

tous

e"r

aw",

orr

:

import

os

os.path.exists(r'C:\windows\example\path')

But

ther

ear

eso

me

othe

rco

nven

ient

func

tions

inos.path

,w

here

path.code.exists()

only

confi

rms

whe

ther

orno

tpa

thex

ists

,th

ere

are

func

tions

whi

chle

tyou

know

ifth

epa

this

afil

e,a

dire

ctor

y,a

mou

ntpo

into

rasy

mlin

k.Th

ere

isev

ena

func

tionos.path.realpath()

whi

chre

veal

sth

etr

uede

stin

atio

nof

asy

mlin

k:

>>>

import

os

>>>

os.path.isfile("/")

Page 288: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

False

>>>

os.path.isfile("/proc/cpuinfo")

True

>>>

os.path.isdir("/")

True

>>>

os.path.isdir("/proc/cpuinfo")

False

>>>

os.path.ismount("/")

True

>>>

os.path.islink("/")

False

>>>

os.path.islink("/vmlinuz")

True

>>>

os.path.realpath("/vmlinuz")

'/boot/vmlinuz-2.6.24-21-generic'

25.3

Com

mon

File

Ope

ratio

ns

Toco

pyor

mov

ea

file,

use

the

shut

illib

rary

.

Page 289: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

import

shutil

shutil.move("originallocation.txt","newlocation.txt")

shutil.copy("original.txt","copy.txt")

Tope

rfor

ma

recu

rsiv

eco

pyit

ispo

ssib

leto

usecopytree()

,to

perf

orm

are

curs

ive

rem

ove

itis

poss

ible

tous

ermtree()

import

shutil

shutil.copytree("dir1","dir2")

shutil.rmtree("dir1")

Tore

mov

ean

indi

vidu

alfil

eth

ere

exis

tsth

eremove()

func

tion

inth

eos

mod

ule:

import

os

os.remove("file.txt")

Page 290: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

26D

atab

ase

Prog

ram

min

g

26.1

Gen

eric

Dat

abas

eC

onne

ctiv

ityus

ing

OD

BC

The

Ope

nD

atab

ase

Con

nect

ivity

1(O

DB

C)A

PIst

anda

rdal

low

str

ansp

aren

tco

nnec

tions

with

any

data

base

that

supp

orts

the

inte

rfac

e.T

his

incl

udes

mos

tpo

pula

rdat

abas

es,s

uch

asPo

stgr

eSQ

L2

orM

icro

soft

Acc

ess3 .T

hest

reng

ths

1http://en.wikipedia.org/wiki/Open%20Database%

20Connectivity

2http://en.wikipedia.org/wiki/PostgreSQL

3http://en.wikipedia.org/wiki/Microsoft%20Access

283

Page 291: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

ofus

ing

this

inte

rfac

eis

that

aPy

thon

scrip

torm

odul

eca

nbe

used

ondi

ffer

ent

data

base

sby

only

mod

ifyi

ngth

eco

nnec

tion

stri

ng.

The

rear

eth

ree

OD

BC

mod

ules

forP

ytho

n:

1.Py

thon

Win

OD

BC

Mod

ule:

prov

ided

byM

ark

Ham

mon

dw

ithth

ePy

thon

Win

4pa

ckag

efo

rMic

roso

ftW

indo

ws

(onl

y).T

his

isa

min

imal

impl

emen

tatio

nof

OD

BC

,and

conf

orm

sto

Ver

sion

1.0

ofth

ePy

thon

Dat

abas

eA

PI.A

lthou

ghit

isst

able

,itw

illlik

ely

notb

ede

velo

ped

any

furt

her.5

2.m

xOD

BC

:a

com

mer

cial

Pyth

onpa

ckag

e(h

ttp://

ww

w.e

geni

x.co

m/p

rodu

cts/

pyth

on/m

xOD

BC

/),6

whi

chfe

atur

esha

ndlin

gof

Dat

eTim

eob

ject

san

dpr

epar

edst

atem

ents

(usi

ngpa

ram

eter

s).

4http://starship.python.net/crew/mhammond/win32/

5H

amm

ond,

M.P

ytho

nPr

ogra

mm

ing

onW

in32

.O'R

eilly

,,20

006

http://www.egenix.com/products/python/mxODBC/),

Page 292: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

3.py

odbc

:an

open

-sou

rce

Pyth

onpa

ckag

e(h

ttp://

code

.goo

gle.

com

/p/p

yodb

c),7

whi

chus

eson

lyna

tive

Pyth

onda

ta-ty

pes

and

uses

prep

ared

stat

emen

tsfo

rinc

reas

edpe

rfor

man

ce.T

hepr

esen

tver

sion

supp

orts

the

Pyth

onD

atab

ase

API

Spec

ifica

tion

v2.0

.8

26.1

.1py

odbc

An

exam

ple

usin

gth

epyodbc

Pyth

onpa

ckag

ew

itha

Mic

roso

ftA

cces

sfil

e(a

lthou

ghth

isda

taba

seco

nnec

tion

coul

dju

stas

easi

lybe

aM

ySQ

Lda

taba

se):

import

pyodbc

DBfile

='/data/MSAccess/Music_Library.mdb'

conn

=pyodbc.connect('DRIVER={Microsoft

Access

Driver

(*.mdb)};DBQ='+DBfile)

cursor

=conn.cursor()

7http://code.google.com/p/pyodbc),

8Py

thon

Dat

abas

eA

PISp

ecifi

catio

nv2

.09 .P

ytho

n.R

etri

eved

Page 293: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

SQL

='SELECT

Artist,

AlbumName

FROM

RecordCollection

ORDER

BY

Year;'

for

row

in

cursor.execute(SQL):

#cursors

are

iterable

printrow.Artist,

row.AlbumName

cursor.close()

conn.close()

Man

ym

ore

feat

ures

and

exam

ples

are

prov

ided

onth

epy

odbc

web

site

.

26.2

Post

gres

conn

ectio

nin

Pyth

on

->se

ePy

thon

Prog

ram

min

g/D

atab

ases

10

10http://en.wikibooks.org/wiki/Python%20Programming%

2FDatabases

Page 294: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

26.3

MyS

QL

conn

ectio

nin

Pyth

on

->se

ePy

thon

Prog

ram

min

g/D

atab

ases

11

26.4

SQL

Alc

hem

yin

Act

ion

SQL

Alc

hem

yha

sbe

com

eth

efa

vori

tech

oice

form

any

larg

ePy

thon

proj

ects

that

use

data

base

s.A

long

,up

date

dlis

tof

such

proj

ects

islis

ted

onth

eSQ

LA

lche

my

site

.Add

ition

ally

,apr

etty

good

tuto

rial

can

befo

und

ther

e,as

wel

l.A

long

with

ath

inda

taba

sew

rapp

er,E

lixir,

itbe

have

sve

rysi

mila

rly

toth

eO

RM

inR

ails

,Act

iveR

ecor

d.

11http://en.wikibooks.org/wiki/Python%20Programming%

2FDatabases

Page 295: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

26.5

See

also

•Py

thon

Prog

ram

min

g/D

atab

ases

12

26.6

Ref

eren

ces

26.7

Ext

erna

llin

ks

•SQ

LA

lche

my13

•SQ

LO

bjec

t14

•PE

P24

915-P

ytho

nD

atab

ase

API

Spec

ifica

tion

v2.0

12http://en.wikibooks.org/wiki/Python%20Programming%

2FDatabases

13http://www.sqlalchemy.org/

14http://www.sqlobject.org/

15http://www.python.org/dev/peps/pep-0249/

Page 296: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•D

atab

ase

Topi

cG

uide

16on

pyth

on.o

rg

16http://www.python.org/doc/topics/database/

Page 297: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 298: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

27W

ebPa

geH

arve

stin

g

291

Page 299: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 300: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

28T

hrea

ding

Thr

eadi

ngin

pyth

onis

used

toru

nm

ultip

leth

read

s(t

asks

,fun

ctio

nca

lls)a

tth

esa

me

time.

Not

eth

atth

isdo

esno

tmea

n,th

atth

eyar

eex

ecut

edon

diff

eren

tC

PUs.

Pyth

onth

read

sw

illN

OT

mak

eyo

urpr

ogra

mfa

ster

ifit

alre

ady

uses

100

%C

PUtim

e,pr

obab

lyyo

uth

enw

antt

olo

okin

topa

ralle

lpro

gram

min

g.If

you

are

inte

rest

edin

para

llelp

roga

mm

ing

with

pyth

on,p

leas

ese

ehe

re1 .

Pyth

onth

read

sar

eus

edin

case

sw

here

the

exec

utio

nof

ata

skin

volv

esso

me

wai

ting.

One

exam

ple

wou

ldbe

inte

ract

ion

with

ase

rvic

eho

sted

onan

othe

r

1http://wiki.python.org/moin/ParallelProcessing

293

Page 301: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

com

pute

r,su

chas

aw

ebse

rver

.Thr

eadi

ngal

low

spy

thon

toex

ecut

eot

herc

ode

whi

lew

aitin

g;th

isis

easi

lysi

mul

ated

with

the

slee

pfu

nctio

n.

28.1

Exa

mpl

es

28.1

.1A

Min

imal

Exa

mpl

ew

ithFu

nctio

nC

all

Mak

ea

thre

adth

atpr

ints

num

bers

from

1-10

,wai

tsfo

r1se

cbe

twee

n:

import

thread

import

time

def

loop1_10():

fori

in

range(1,

11):

time.sleep(1)

print(i)

thread.start_new_thread(loop1_10,

())

Page 302: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

28.1

.2A

Min

imal

Exa

mpl

ew

ithO

bjec

t

#!/usr/bin/env

python

import

threading

import

time

from

__future__

import

print_function

class

MyThread(threading.Thread):

defrun(self):

print("{}

started!".format(self.getName()))

#"Thread-x

started!"

time.sleep(1)

#Pretend

to

workfora

second

print("{}

finished!".format(self.getName()))

#"Thread-x

finishsed!"

if

__name__==

'__main__':

forx

in

range(4):

#Four

times... mythread

=MyThread(name

="Thread-{}".format(x

+1))

#...Instantiate

athread

andpass

aunique

ID

to

it

mythread.start()

#...Start

the

thread

Page 303: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

time.sleep(.9)

#...Wait

0.9

seconds

before

starting

another

Thi

ssh

ould

outp

ut:

Thread-1

started!

Thread-2

started!

Thread-1

finished!

Thread-3

started!

Thread-2

finished!

Thread-4

started!

Thread-3

finished!

Thread-4

finished!

Not

e:th

isex

ampl

eap

pear

sto

cras

hID

LE

inW

indo

ws

XP

(see

ms

tow

ork

inID

LE

1.2.

4in

Win

dow

sX

Pth

ough

)

The

rese

ems

tobe

apr

oble

mw

ithth

is,i

fyou

repl

ace

Slee

p(1)

with

(2),

and

chan

gera

nge

(4)

tora

nge(

10).

Thr

ead

-2fin

ishe

dis

the

first

line

befo

reits

even

star

ted.

inW

ING

IDE

,Net

bean

s,ec

lipse

isfin

e.

Page 304: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

29E

xten

ding

with

C

Thi

sgi

ves

am

inim

alE

xam

ple

onho

wto

Ext

end

Pyth

onw

ithC

.Lin

uxis

used

forb

uild

ing

(fee

lfre

eto

exte

ndit

foro

ther

Plat

form

s).I

fyou

have

any

prob

lem

s,pl

ease

repo

rtth

em(e

.g.o

nth

edi

cuss

ion

page

),Iw

illch

eck

back

ina

whi

lean

dtr

yto

sort

them

out.

29.1

Usi

ngth

ePy

thon

/CA

PI

On

anU

bunt

usy

stem

,you

mig

htne

edto

run

297

Page 305: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

$sudo

apt-get

install

python-dev

•ht

tp://

docs

.pyt

hon.

org/

ext/e

xt.h

tml

•ht

tp://

docs

.pyt

hon.

org/

api/a

pi.h

tml

29.1

.1A

min

imal

exam

ple

The

min

imal

exam

ple

we

will

crea

teno

wis

very

sim

ilari

nbe

havi

ourt

oth

efo

llow

ing

pyth

onsn

ippe

t:

def

say_hello(name):

"Greet

somebody."

print"Hello

%s!"

%name

Page 306: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

Cso

urce

code

(hellomodule.c

)

#include

<Python.h>

static

PyObject*

say_hello(PyObject*self,

PyObject*args)

{constchar*

name;

if(!PyArg_ParseTuple(args,

"s",

&name))

returnNULL;

printf("Hello

%s!\n",

name);

Py_RETURN_NONE;

} static

PyMethodDef

HelloMethods[]

={

{"say_hello",

say_hello,

METH_VARARGS,

"Greet

somebody."},

{NULL,

NULL,

0,

NULL}

};

PyMODINIT_FUNC

Page 307: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

inithello(void)

{(void)

Py_InitModule("hello",

HelloMethods);

} Bui

ldin

gth

eex

tens

ion

mod

ule

with

GC

Cfo

rL

inux

Tobu

ildou

rext

ensi

onm

odul

ew

ecr

eate

the

filesetup.py

like:

from

distutils.core

import

setup,

Extension

module1

=Extension('hello',

sources

=['hellomodule.c'])

setup

(name

='PackageName',

version

='1.0',

description

='This

is

ademo

package',

ext_modules

=[module1])

Now

we

can

build

ourm

odul

ew

ith

Page 308: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

python

setup.py

build

The

mod

ulehello.so

will

end

upinbuild/lib.linux-i686-x.y

.

Bui

ldin

gth

eex

tens

ion

mod

ule

with

GC

Cfo

rM

icro

soft

Win

dow

s

Mic

roso

ftW

indo

ws

user

sca

nus

eM

inG

W1

toco

mpi

leth

isfr

omcmd.exe2

usin

ga

sim

ilar

met

hod

toL

inux

user

,as

show

nab

ove.

Ass

umin

ggcc

isin

thePATH

envi

ronm

entv

aria

ble,

type

:

python

setup.py

build

-cmingw32

1http://en.wikipedia.org/wiki/MinGW

2http://en.wikipedia.org/wiki/cmd.exe

Page 309: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

mod

ulehello.pyd

will

end

upinbuild\lib.win32-x.y

,whi

chis

aPy

thon

Dyn

amic

Mod

ule

(sim

ilart

oaDLL

).

An

alte

rnat

ew

ayof

build

ing

the

mod

ule

inW

indo

ws

isto

build

aD

LL

.(T

his

met

hod

does

notn

eed

anex

tens

ion

mod

ule

file)

.Fro

mcmd.exe

,typ

e:

gcc

-c

hellomodule.c

-I/PythonXY/include

gcc

-shared

hellomodule.o

-L/PythonXY/libs

-lpythonXY-o

hello.dll

whe

reX

Yre

pres

ents

the

vers

ion

ofPy

thon

,suc

has

"24"

forv

ersi

on2.

4.

Bui

ldin

gth

eex

tens

ion

mod

ule

usin

gM

icro

soft

Vis

ualC

++

With

VC

8di

stut

ilsis

brok

en.

We

will

use

cl.e

xefr

oma

com

man

dpr

ompt

inst

ead:

Page 310: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

cl

/LD

hellomodule.c

/Ic:\Python24\include

c:\Python24\libs\python24.lib

/link/out:hello.dll

Usi

ngth

eex

tens

ion

mod

ule

Cha

nge

toth

esu

bdir

ecto

ryw

here

the

file

‘hel

lo.s

o‘re

side

s.In

anin

tera

ctiv

epy

thon

sess

ion

you

can

use

the

mod

ule

asfo

llow

s.

>>>

import

hello

>>>

hello.say_hello("World")

Hello

World!

Page 311: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

29.1

.2A

mod

ule

for

calc

ulat

ing

fibon

acci

num

bers

The

Cso

urce

code

(fibm

odul

e.c)

#include

<Python.h>

int

_fib(intn)

{if(n

<2)

returnn;

elsereturn_fib(n-1)

+_fib(n-2);

} static

PyObject*fib(PyObject*self,

PyObject*args)

{intn;

if(!PyArg_ParseTuple(args,

"i",

&n))

returnNULL;

returnPy_BuildValue("i",

_fib(n));

}

Page 312: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

static

PyMethodDef

FibMethods[]

={

{"fib",

fib,

METH_VARARGS,

"Calculate

the

Fibonacci

numbers."},

{NULL,

NULL,

0,

NULL}

};

PyMODINIT_FUNC

initfib(void)

{(void)

Py_InitModule("fib",

FibMethods);

} The

build

scri

pt(s

etup

.py)

from

distutils.core

import

setup,

Extension

module1

=Extension('fib',

sources

=['fibmodule.c'])

setup

(name

='PackageName',

version

='1.0',

description

='This

is

ademo

package',

ext_modules

=[module1])

Page 313: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

How

tous

eit?

>>>

import

fib

>>>

fib.fib(10)

55

29.2

Usi

ngSW

IG

Cre

atin

gth

epr

evio

usex

ampl

eus

ing

SWIG

ism

uch

mor

est

raig

htfo

rwar

d.To

follo

wth

ispa

thyo

une

edto

get

SWIG

3up

and

runn

ing

first

.To

inst

alli

ton

anU

bunt

usy

stem

,you

mig

htne

edto

run

the

follo

win

gco

mm

ands

$sudo

apt-get

install

libboost-python-dev

$sudo

apt-get

install

python-dev

Aft

erth

atcr

eate

two

files

.

3http://www.swig.org/

Page 314: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

/*hellomodule.c*/

#include

<stdio.h>

void

say_hello(constchar*name)

{printf("Hello

%s!\n",

name);

} /*hello.i*/

%module

hello

extern

voidsay_hello(constchar*name);

Now

com

esth

em

ore

diffi

cult

part

,glu

ing

ital

ltog

ethe

r.

Firs

twe

need

tole

tSW

IGdo

itsw

ork.

swig

-python

hello.i

Thi

sgi

ves

usth

efil

es‘h

ello

.py‘

and

‘hel

lo_w

rap.

c‘.

Page 315: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

next

step

isco

mpi

ling

(sub

stitu

te/u

sr/in

clud

e/py

thon

2.4/

with

the

corr

ect

path

fory

ours

etup

!).

gcc

-fpic

-c

hellomodule.c

hello_wrap.c

-I/usr/include/python2.4/

Now

linki

ngan

dw

ear

edo

ne!

gcc

-shared

hellomodule.o

hello_wrap.o

-o

_hello.so

The

mod

ule

isus

edin

the

follo

win

gw

ay.

>>>

import

hello

>>>

hello.say_hello("World")

Hello

World!

Page 316: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

30E

xten

ding

with

C++

Boo

st.P

ytho

n1is

the

defa

cto

stan

dard

for

wri

ting

C++

2ex

tens

ion

mod

ules

.B

oost

.Pyt

hon

com

esbu

ndle

dw

ithth

eB

oost

C++

Lib

rari

es3 .T

oin

stal

lito

nan

Ubu

ntu

syst

em,y

oum

ight

need

toru

nth

efo

llow

ing

com

man

ds

$sudo

apt-get

install

libboost-python-dev

$sudo

apt-get

install

python-dev

1http://www.boost.org/libs/python/doc/

2http://en.wikibooks.org/wiki/C%2B%2B

3http://www.boost.org/

309

Page 317: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

30.1

AH

ello

Wor

ldE

xam

ple

30.1

.1T

heC

++so

urce

code

(hel

lom

odul

e.cp

p)

#include

<iostream>

using

namespace

std;

void

say_hello(constchar*name)

{cout

<<

"Hello

"<<

name

<<

"!\n";

} #include

<boost/python/module.hpp>

#include

<boost/python/def.hpp>

using

namespace

boost::python;

BOOST_PYTHON_MODULE(hello)

{def("say_hello",

say_hello);

}

Page 318: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

30.1

.2se

tup.

py

#!/usr/bin/env

python

from

distutils.core

import

setup

from

distutils.extension

import

Extension

setup(name="PackageName",

ext_modules=[

Extension("hello",

["hellomodule.cpp"],

libraries

=["boost_python"])

])

Now

we

can

build

ourm

odul

ew

ith

python

setup.py

build

The

mod

ule

‘hel

lo.s

o‘w

illen

dup

ine.

g‘b

uild

/lib.

linux

-i68

6-2.

4‘.

Page 319: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

30.1

.3U

sing

the

exte

nsio

nm

odul

e

Cha

nge

toth

esu

bdir

ecto

ryw

here

the

file

‘hel

lo.s

o‘re

side

s.In

anin

tera

ctiv

epy

thon

sess

ion

you

can

use

the

mod

ule

asfo

llow

s.

>>>

import

hello

>>>

hello.say_hello("World")

Hello

World!

30.2

An

exam

ple

with

CG

AL

Som

e,bu

tnot

all,

func

tions

ofth

eC

GA

Llib

rary

have

alre

ady

Pyth

onbi

ndin

gs.

Her

ean

exam

ple

ispr

ovid

edfo

raca

sew

ithou

tsuc

ha

bind

ing

and

how

itm

ight

beim

plem

ente

d.T

heex

ampl

eis

take

nfr

omth

eC

GA

LD

ocum

enta

tion4 .

4http://www.cgal.org/Manual/3.3/doc_html/cgal_manual/

SearchStructures/Chapter_main.html#Subsection_46.5.1

Page 320: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

//

test.cpp

using

namespace

std;

/*

PYTHON*/

#include

<boost/python.hpp>

#include

<boost/python/module.hpp>

#include

<boost/python/def.hpp>

namespace

python

=boost::python;

/*

CGAL*/

#include

<CGAL/Cartesian.h>

#include

<CGAL/Range_segment_tree_traits.h>

#include

<CGAL/Range_tree_k.h>

typedef

CGAL::Cartesian<double>

K;

typedef

CGAL::Range_tree_map_traits_2<K,

char>

Traits;

typedef

CGAL::Range_tree_2<Traits>

Range_tree_2_type;

typedef

Traits::Key

Key;

typedef

Traits::Interval

Interval;

Range_tree_2_type

*Range_tree_2

=newRange_tree_2_type;

void

create_tree()

{

Page 321: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

typedefTraits::Key

Key;

typedefTraits::Interval

Interval;

std::vector<Key>

InputList,

OutputList;

InputList.push_back(Key(K::Point_2(8,5.1),

'a'));

InputList.push_back(Key(K::Point_2(1.0,1.1),

'b'));

InputList.push_back(Key(K::Point_2(3,2.1),

'c'));

Range_tree_2->make_tree(InputList.begin(),InputList.end());

Interval

win(Interval(K::Point_2(1,2.1),K::Point_2(8.1,8.2)));

std::cout

<<

"\n

Window

Query:\n";

Range_tree_2->window_query(win,

std::back_inserter(OutputList));

std::vector<Key>::iterator

current=OutputList.begin();

while(current!=OutputList.end()){

std::cout

<<

""

<<

(*current).first.x()

<<

","

<<

(*current).first.y()

<<

":"

<<

(*current).second

<<

std::endl;

current++;

}std::cout

<<

"\n

Done\n";

} void

initcreate_tree()

{;}

Page 322: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

using

namespace

boost::python;

BOOST_PYTHON_MODULE(test)

{def("create_tree",

create_tree,

"");

} //

setup.py

#!/usr/bin/env

python

from

distutils.core

import

setup

from

distutils.extension

import

Extension

setup(name="PackageName",

ext_modules=[

Extension("test",

["test.cpp"],

libraries

=["boost_python"])

])

We

then

com

pile

and

run

the

mod

ule

asfo

llow

s:

Page 323: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

$python

setup.py

build

$cd

build/lib*

$python

>>>

import

test

>>>

test.create_tree()

Window

Query:

3,2.1:c

8,5.1:a

Done

>>>

30.3

Han

dlin

gPy

thon

obje

ctsa

nder

rors

One

can

also

hand

lem

ore

com

plex

data

,e.g

.Py

thon

obje

cts

like

lists

.T

heat

trib

utes

are

acce

ssed

with

the

extr

actf

unct

ion

exec

uted

onth

eob

ject

s"a

ttr"

func

tion

outp

ut.W

eca

nal

soth

row

erro

rsby

telli

ngth

elib

rary

that

aner

rorh

asoc

curr

edan

dre

turn

ing.

Inth

efo

llow

ing

case

,we

have

writ

ten

aC

++fu

nctio

nca

lled

"afu

nctio

n"w

hich

we

wan

tto

call.

The

func

tion

take

san

inte

gerN

and

Page 324: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

ave

ctor

ofle

ngth

Nas

inpu

t,w

eha

veto

conv

ertt

hepy

thon

listt

oa

vect

orof

stri

ngs

befo

reca

lling

the

func

tion.

#include

<vector>

using

namespace

std;

void

_afunction_wrapper(intN,

boost::python::list

mapping)

{

intmapping_length

=boost::python::extract<int>(mapping.attr("__len__")());

//Do

Error

checking,

the

mapping

needs

to

be

at

least

as

long

as

Nif(mapping_length

<N)

{PyErr_SetString(PyExc_ValueError,

"The

string

mapping

must

be

at

least

of

length

N");

boost::python::throw_error_already_set();

return;

} vector<string>

mystrings(mapping_length);

for(inti=0;

i<mapping_length;

i++)

{mystrings[i]

=boost::python::extract<charconst

*>(mapping[i]);

}

Page 325: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

//now

call

our

C++

function

_afunction(N,

mystrings);

} using

namespace

boost::python;

BOOST_PYTHON_MODULE(c_afunction)

{def("afunction",

_afunction_wrapper);

}

Page 326: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

31W

SGIw

ebpr

ogra

mm

ing

319

Page 327: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 328: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

32W

SGIW

ebPr

ogra

mm

ing

32.1

Ext

erna

lRes

ourc

es

http

://do

cs.p

ytho

n.or

g/lib

rary

/wsg

iref

.htm

l

321

Page 329: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 330: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

33R

efer

ence

s

33.1

Lan

guag

ere

fere

nce

The

late

stdo

cum

enta

tion

for

the

stan

dard

pyth

onlib

rari

esan

dm

odul

esca

nal

way

sbe

foun

dat

The

Pyth

on.o

rgdo

cum

ents

sect

ion1

1http://www.python.org/doc/

323

Page 331: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

33.2

Ext

erna

llin

ks

•Py

thon

book

sav

aila

ble

forf

ree

dow

nloa

d2

•N

on-p

rogr

amm

ers

pyth

ontu

tori

al3

dona

ted

toth

ispr

ojec

t.W

ikiv

ersi

on4

•D

ive

into

Pyth

on5

•H

owto

thin

kL

ike

aC

ompu

terS

cien

tist:

Lea

rnin

gw

ithPy

thon

6

•A

Byt

eof

Pyth

on7

•A

ctiv

eSta

tePy

thon

Coo

kboo

k8

•Te

xtPr

oces

sing

inPy

thon

9

2http://www.techbooksforfree.com/perlpython.shtml

3http://www.honors.montana.edu/~jjc/easytut/easytut/

4http://en.wikibooks.org/wiki/User%3AJrincayc%2FContents

5http://www.diveintopython.org/

6http://www.ibiblio.org/obp/thinkCSpy/

7http://www.byteofpython.info/

8http://aspn.activestate.com/ASPN/Python/Cookbook/

9http://gnosis.cx/TPiP/

Page 332: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•D

evSh

ed's

Pyth

onTu

tori

als10

•M

akeB

ot11

-Sim

ple

Pyth

onID

Ede

sign

edfo

rtea

chin

gga

me

prog

ram

min

gto

kids

.•

SPE

-Sta

ni's

Pyth

onE

dito

r12

10http://www.devshed.com/c/b/Python/

11http://stratolab.com/misc/makebot

12http://pythonide.stani.be

Page 333: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 334: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

34A

utho

rs

34.1

Aut

hors

ofPy

thon

text

book

•Q

uart

z251

•Je

sdis

cipl

e2

•H

anne

sR

öst3

1http://en.wikibooks.org/wiki/User%3AQuartz25

2http://en.wikibooks.org/wiki/User%3AJesdisciple

3http://en.wikibooks.org/wiki/User%3AHannes%20R%F6st

327

Page 335: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 336: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

35C

ontr

ibut

ors

Edi

tsU

ser

1A

deel

q1

3A

dria

tikus

2

3A

drig

nola

3

1A

horn

edal

4

4A

lbm

ont5

1http://en.wikibooks.org/w/index.php?title=User:Adeelq

2http://en.wikibooks.org/w/index.php?title=User:Adriatikus

3http://en.wikibooks.org/w/index.php?title=User:Adrignola

4http://en.wikibooks.org/w/index.php?title=User:Ahornedal

5http://en.wikibooks.org/w/index.php?title=User:Albmont

329

Page 337: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2A

lexa

nder

2566

1A

peig

ne7

1A

rrow

Stom

per8

50A

rtev

elde

9

2A

uk10

1A

vice

nnas

is11

1A

z156

812

1B

aiju

m81

13

6http://en.wikibooks.org/w/index.php?title=User:

Alexander256

7http://en.wikibooks.org/w/index.php?title=User:Apeigne

8http://en.wikibooks.org/w/index.php?title=User:

ArrowStomper

9http://en.wikibooks.org/w/index.php?title=User:Artevelde

10http://en.wikibooks.org/w/index.php?title=User:Auk

11http://en.wikibooks.org/w/index.php?title=User:Avicennasis

12http://en.wikibooks.org/w/index.php?title=User:Az1568

13http://en.wikibooks.org/w/index.php?title=User:Baijum81

Page 338: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1B

eary

60514

1B

ehna

m15

2B

elan

d16

1B

enro

lfe17

2B

etal

pha18

3B

ittne

r19

20B

obG

ibso

n20

1B

oyom

bo21

1B

rian

McE

rlea

n22

14http://en.wikibooks.org/w/index.php?title=User:Beary605

15http://en.wikibooks.org/w/index.php?title=User:Behnam

16http://en.wikibooks.org/w/index.php?title=User:Beland

17http://en.wikibooks.org/w/index.php?title=User:Benrolfe

18http://en.wikibooks.org/w/index.php?title=User:Betalpha

19http://en.wikibooks.org/w/index.php?title=User:Bittner

20http://en.wikibooks.org/w/index.php?title=User:BobGibson

21http://en.wikibooks.org/w/index.php?title=User:Boyombo

22http://en.wikibooks.org/w/index.php?title=User:Brian_

McErlean

Page 339: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

13C

Wii23

1C

affe

inat

edPo

nder

er24

1C

burn

ett25

1C

hese

mon

kylo

ma26

6C

huck

hoff

man

n27

1C

loro

x28

2C

onve

x29

2C

ribe

30

23http://en.wikibooks.org/w/index.php?title=User:CWii

24http://en.wikibooks.org/w/index.php?title=User:

CaffeinatedPonderer

25http://en.wikibooks.org/w/index.php?title=User:Cburnett

26http://en.wikibooks.org/w/index.php?title=User:

Chesemonkyloma

27http://en.wikibooks.org/w/index.php?title=User:

Chuckhoffmann

28http://en.wikibooks.org/w/index.php?title=User:Clorox

29http://en.wikibooks.org/w/index.php?title=User:Convex

30http://en.wikibooks.org/w/index.php?title=User:Cribe

Page 340: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1C

spur

rier

31

2D

aKra

zyJa

k32

1D

aem

onax

33

1D

anie

lkha

shab

i34

43D

arkl

ama35

1D

avid

Car

y36

11D

avid

Ros

s37

2D

bolto

n38

31http://en.wikibooks.org/w/index.php?title=User:Cspurrier

32http://en.wikibooks.org/w/index.php?title=User:DaKrazyJak

33http://en.wikibooks.org/w/index.php?title=User:Daemonax

34http://en.wikibooks.org/w/index.php?title=User:

Danielkhashabi

35http://en.wikibooks.org/w/index.php?title=User:Darklama

36http://en.wikibooks.org/w/index.php?title=User:DavidCary

37http://en.wikibooks.org/w/index.php?title=User:DavidRoss

38http://en.wikibooks.org/w/index.php?title=User:Dbolton

Page 341: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

2D

eep

shob

hit39

4D

erbe

th40

1D

irk

Hün

nige

r41

4D

rago

necc

42

6D

risc

oll43

1E

dlea

fe44

1E

doD

odo45

3E

lieD

eBra

uwer

46

39http://en.wikibooks.org/w/index.php?title=User:Deep_

shobhit

40http://en.wikibooks.org/w/index.php?title=User:Derbeth

41http://en.wikibooks.org/w/index.php?title=User:Dirk_H%C3%

BCnniger

42http://en.wikibooks.org/w/index.php?title=User:Dragonecc

43http://en.wikibooks.org/w/index.php?title=User:Driscoll

44http://en.wikibooks.org/w/index.php?title=User:Edleafe

45http://en.wikibooks.org/w/index.php?title=User:EdoDodo

46http://en.wikibooks.org/w/index.php?title=User:

ElieDeBrauwer

Page 342: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1E

ric

Silv

a47

1Fe

rran

Jorb

a48

8Fi

shpi

49

21Fl

arel

ocke

50

1Fo

xj51

1Fr

y-ku

n52

2G

asto

553

1G

reyw

eath

er54

1G

uana

bot55

47http://en.wikibooks.org/w/index.php?title=User:Eric_Silva

48http://en.wikibooks.org/w/index.php?title=User:FerranJorba

49http://en.wikibooks.org/w/index.php?title=User:Fishpi

50http://en.wikibooks.org/w/index.php?title=User:Flarelocke

51http://en.wikibooks.org/w/index.php?title=User:Foxj

52http://en.wikibooks.org/w/index.php?title=User:Fry-kun

53http://en.wikibooks.org/w/index.php?title=User:Gasto5

54http://en.wikibooks.org/w/index.php?title=User:Greyweather

55http://en.wikibooks.org/w/index.php?title=User:Guanabot

Page 343: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1G

uana

co56

4G

utw

orth

57

4H

agin

daz58

25H

anne

sR

öst59

2H

owip

eppe

r60

15H

yper

geek

1461

3IO

62

2Im

apie

kind

aguy

63

56http://en.wikibooks.org/w/index.php?title=User:Guanaco

57http://en.wikibooks.org/w/index.php?title=User:Gutworth

58http://en.wikibooks.org/w/index.php?title=User:Hagindaz

59http://en.wikibooks.org/w/index.php?title=User:Hannes_R%

C3%B6st

60http://en.wikibooks.org/w/index.php?title=User:Howipepper

61http://en.wikibooks.org/w/index.php?title=User:Hypergeek14

62http://en.wikibooks.org/w/index.php?title=User:IO

63http://en.wikibooks.org/w/index.php?title=User:

Imapiekindaguy

Page 344: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1In

tgr64

3Ir

vin.

sha65

4Ja

ckPo

tte66

2Je

rf67

1Je

sdis

cipl

e68

32Jg

uk69

1Jo

nath

anW

eble

y70

1Jo

nbry

an71

1K

ayau

72

64http://en.wikibooks.org/w/index.php?title=User:Intgr

65http://en.wikibooks.org/w/index.php?title=User:Irvin.sha

66http://en.wikibooks.org/w/index.php?title=User:JackPotte

67http://en.wikibooks.org/w/index.php?title=User:Jerf

68http://en.wikibooks.org/w/index.php?title=User:Jesdisciple

69http://en.wikibooks.org/w/index.php?title=User:Jguk

70http://en.wikibooks.org/w/index.php?title=User:Jonathan_

Webley

71http://en.wikibooks.org/w/index.php?title=User:Jonbryan

72http://en.wikibooks.org/w/index.php?title=User:Kayau

Page 345: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1K

erni

gh73

11L

Dir

acD

elta

74

1L

egok

tm75

1L

ena2

28976

4L

eopo

ldau

gust

sson

77

3L

ogic

theo

78

1M

MJ79

1M

anue

lGR

80

73http://en.wikibooks.org/w/index.php?title=User:Kernigh

74http://en.wikibooks.org/w/index.php?title=User:LDiracDelta

75http://en.wikibooks.org/w/index.php?title=User:Legoktm

76http://en.wikibooks.org/w/index.php?title=User:Lena2289

77http://en.wikibooks.org/w/index.php?title=User:Leopold_

augustsson

78http://en.wikibooks.org/w/index.php?title=User:Logictheo

79http://en.wikibooks.org/w/index.php?title=User:MMJ

80http://en.wikibooks.org/w/index.php?title=User:ManuelGR

Page 346: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

5M

arce

loA

rauj

o81

1M

attz

azam

i82

1M

axim

kolo

sov83

4M

icro

dot84

1M

ithri

ll200

285

1M

onob

i86

32M

r.Z-m

an87

2M

shon

le88

81http://en.wikibooks.org/w/index.php?title=User:

MarceloAraujo

82http://en.wikibooks.org/w/index.php?title=User:Mattzazami

83http://en.wikibooks.org/w/index.php?title=User:Maxim_

kolosov

84http://en.wikibooks.org/w/index.php?title=User:Microdot

85http://en.wikibooks.org/w/index.php?title=User:

Mithrill2002

86http://en.wikibooks.org/w/index.php?title=User:Monobi

87http://en.wikibooks.org/w/index.php?title=User:Mr.Z-man

88http://en.wikibooks.org/w/index.php?title=User:Mshonle

Page 347: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

17M

wto

ews89

3M

yuru

rdur

maz

90

2N

313t

391

3N

ikai

92

1N

ikhi

l389

93

1N

ithin

Bek

al94

1O

ffpa

th95

6Pa

nic2

k496

1Pa

vlix

97

89http://en.wikibooks.org/w/index.php?title=User:Mwtoews

90http://en.wikibooks.org/w/index.php?title=User:

Myururdurmaz

91http://en.wikibooks.org/w/index.php?title=User:N313t3

92http://en.wikibooks.org/w/index.php?title=User:Nikai

93http://en.wikibooks.org/w/index.php?title=User:Nikhil389

94http://en.wikibooks.org/w/index.php?title=User:NithinBekal

95http://en.wikibooks.org/w/index.php?title=User:Offpath

96http://en.wikibooks.org/w/index.php?title=User:Panic2k4

97http://en.wikibooks.org/w/index.php?title=User:Pavlix

Page 348: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

22Pd

illey

98

1Pe

rey99

1Pe

tepa

rke10

0

1Pi

ngve

no10

1

4Q

uart

z2510

2

4Q

uite

Unu

sual

103

3Q

wer

tyus

104

2R

dnk10

5

98http://en.wikibooks.org/w/index.php?title=User:Pdilley

99http://en.wikibooks.org/w/index.php?title=User:Perey

100http://en.wikibooks.org/w/index.php?title=User:Peteparke

101http://en.wikibooks.org/w/index.php?title=User:Pingveno

102http://en.wikibooks.org/w/index.php?title=User:Quartz25

103http://en.wikibooks.org/w/index.php?title=User:

QuiteUnusual

104http://en.wikibooks.org/w/index.php?title=User:Qwertyus

105http://en.wikibooks.org/w/index.php?title=User:Rdnk

Page 349: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1R

ecen

tRun

es10

6

1R

emi0

o107

31R

emot

e108

3R

icha

rd00

1109

3R

obm

35111

0

1R

yanP

enne

r111

14Si

gma

7112

4Si

ngin

gwol

fboy

113

106http://en.wikibooks.org/w/index.php?title=User:Recent_

Runes

107http://en.wikibooks.org/w/index.php?title=User:Remi0o

108http://en.wikibooks.org/w/index.php?title=User:Remote

109http://en.wikibooks.org/w/index.php?title=User:Richard001

110http://en.wikibooks.org/w/index.php?title=User:Robm351

111http://en.wikibooks.org/w/index.php?title=User:RyanPenner

112http://en.wikibooks.org/w/index.php?title=User:Sigma_7

113http://en.wikibooks.org/w/index.php?title=User:

Singingwolfboy

Page 350: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1Sm

alls

1234

5611

4

1So

l115

1St

ephe

nFer

g116

2Su

chen

wi11

7

6Sz

eesh

anal

inaq

vi11

8

1Te

cky2

119

1Te

dzzz

1120

3T

heK

id12

1

114http://en.wikibooks.org/w/index.php?title=User:

Smalls123456

115http://en.wikibooks.org/w/index.php?title=User:Sol

116http://en.wikibooks.org/w/index.php?title=User:StephenFerg

117http://en.wikibooks.org/w/index.php?title=User:Suchenwi

118http://en.wikibooks.org/w/index.php?title=User:

Szeeshanalinaqvi

119http://en.wikibooks.org/w/index.php?title=User:Tecky2

120http://en.wikibooks.org/w/index.php?title=User:Tedzzz1

121http://en.wikibooks.org/w/index.php?title=User:The_Kid

Page 351: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

9T

hedj

inn12

2

18T

hund

erbo

lt1612

3

2To

bych

124

2To

mM

orri

s125

1Tr

eilly

126

2U

nion

haw

k127

23W

ebaw

are12

8

1W

enha

ospa

rty12

9

122http://en.wikibooks.org/w/index.php?title=User:The_djinn

123http://en.wikibooks.org/w/index.php?title=User:

Thunderbolt16

124http://en.wikibooks.org/w/index.php?title=User:Tobych

125http://en.wikibooks.org/w/index.php?title=User:Tom_Morris

126http://en.wikibooks.org/w/index.php?title=User:Treilly

127http://en.wikibooks.org/w/index.php?title=User:Unionhawk

128http://en.wikibooks.org/w/index.php?title=User:Webaware

129http://en.wikibooks.org/w/index.php?title=User:

Wenhaosparty

Page 352: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

1W

hym

130

1W

ikiN

azi13

1

1W

ilbur

.har

vey13

2

59W

ithin

focu

s133

1W

olf1

0413

4

20Y

ath13

5

136

130http://en.wikibooks.org/w/index.php?title=User:Whym

131http://en.wikibooks.org/w/index.php?title=User:WikiNazi

132http://en.wikibooks.org/w/index.php?title=User:Wilbur.

harvey

133http://en.wikibooks.org/w/index.php?title=User:Withinfocus

134http://en.wikibooks.org/w/index.php?title=User:Wolf104

135http://en.wikibooks.org/w/index.php?title=User:Yath

136http://en.wikibooks.org/w/index.php?title=User:%CE%A3

Page 353: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 354: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Lis

tofF

igur

es

•G

FDL

:Gnu

Free

Doc

umen

tatio

nL

icen

se.http://www.gnu.org/

licenses/fdl.html

•cc

-by-

sa-3

.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

Shar

eAlik

e3.

0L

icen

se.

http://creativecommons.org/licenses/by-sa/3.0/

•cc

-by-

sa-2

.5:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

Shar

eAlik

e2.

5L

icen

se.

http://creativecommons.org/licenses/by-sa/2.5/

•cc

-by-

sa-2

.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

Shar

eAlik

e2.

0L

icen

se.

http://creativecommons.org/licenses/by-sa/2.0/

347

Page 355: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•cc

-by-

sa-1

.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

Shar

eAlik

e1.

0L

icen

se.

http://creativecommons.org/licenses/by-sa/1.0/

•cc

-by-

2.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.0

Lic

ense

.http://

creativecommons.org/licenses/by/2.0/

•cc

-by-

2.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.0

Lic

ense

.http://

creativecommons.org/licenses/by/2.0/deed.en

•cc

-by-

2.5:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.5

Lic

ense

.http://

creativecommons.org/licenses/by/2.5/deed.en

•cc

-by-

3.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

3.0

Lic

ense

.http://

creativecommons.org/licenses/by/3.0/deed.en

•G

PL:

GN

UG

ener

alPu

blic

Lic

ense

.http://www.gnu.org/

licenses/gpl-2.0.txt

•L

GPL

:G

NU

Les

ser

Gen

eral

Publ

icL

icen

se.http://www.gnu.

org/licenses/lgpl.html

Page 356: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

•PD

:Thi

sim

age

isin

the

publ

icdo

mai

n.

•A

TT

R:

The

copy

righ

tho

lder

ofth

isfil

eal

low

san

yone

tous

eit

for

any

purp

ose,

prov

ided

that

the

copy

righ

thol

der

ispr

oper

lyat

trib

uted

.R

edis

trib

utio

n,de

rivat

ive

wor

k,co

mm

erci

alus

e,an

dal

loth

erus

eis

perm

itted

.

•EU

RO

:Thi

sis

the

com

mon

(rev

erse

)fac

eof

aeu

roco

in.T

heco

pyrig

hton

the

desi

gnof

the

com

mon

face

ofth

eeu

roco

ins

belo

ngs

toth

eE

urop

ean

Com

mis

sion

.Aut

hori

sed

isre

prod

uctio

nin

afo

rmat

with

out

relie

f(dr

awin

gs,p

aint

ings

,film

s)pr

ovid

edth

eyar

eno

tdet

rim

enta

lto

the

imag

eof

the

euro

.

•L

FK:

Liz

enz

Frei

eK

unst

.http://artlibre.org/licence/

lal/de

•C

FR:C

opyr

ight

free

use.

•E

PL:E

clip

sePu

blic

Lic

ense

.http://www.eclipse.org/org/

documents/epl-v10.php

Page 357: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Cop

ies

ofth

eG

PL,t

heL

GPL

asw

ell

asa

GFD

Lar

ein

clud

edin

chap

ter

Lic

ense

s137 .

Plea

seno

teth

atim

ages

inth

epu

blic

dom

ain

dono

tre

quir

eat

tribu

tion.

You

may

clic

kon

the

imag

enu

mbe

rsin

the

follo

win

gta

ble

toop

enth

ew

ebpa

geof

the

imag

esin

your

web

brow

er.

137

Cha

pter

36on

page

353

Page 358: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 359: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248
Page 360: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

36L

icen

ses

36.1

GN

UG

EN

ER

AL

PUB

LIC

LIC

EN

SEV

ersi

on3,

29Ju

ne20

07

Cop

yrig

ht©

2007

Free

Soft

war

eFo

unda

tion,

Inc.

<http

://fs

f.org

/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

not

allo

wed

.Pr

eam

ble

The

GN

UG

ener

alPu

blic

Li-

cens

eis

afr

ee,c

opyl

eftl

icen

sefo

rso

ftw

are

and

othe

rki

nds

ofw

orks

.

The

licen

ses

for

mos

tso

ftw

are

and

othe

rpra

ctic

alw

orks

are

de-

sign

edto

take

away

your

free

-do

mto

shar

ean

dch

ange

the

wor

ks.

By

cont

rast

,th

eG

NU

Gen

eral

Publ

icL

icen

seis

in-

tend

edto

guar

ante

eyo

urfr

ee-

dom

tosh

are

and

chan

geal

lver

-si

onso

fapr

ogra

m–t

om

ake

sure

itre

mai

nsfr

eeso

ftw

are

for

all

itsus

ers.

We,

the

Free

Soft

-w

are

Foun

datio

n,us

eth

eG

NU

Gen

eral

Publ

icL

icen

sefo

rmos

tof

our

soft

war

e;it

appl

ies

also

toan

yot

her

wor

kre

leas

edth

is

way

byits

auth

ors.

You

can

ap-

ply

itto

your

prog

ram

s,to

o.

Whe

nw

esp

eak

offr

eeso

ft-

war

e,w

ear

ere

ferr

ing

tofr

ee-

dom

,no

tpr

ice.

Our

Gen

eral

Publ

icL

icen

ses

are

desi

gned

tom

ake

sure

that

you

have

the

free

-do

mto

dist

ribu

teco

pies

offr

eeso

ftw

are

(and

char

gefo

rth

emif

you

wis

h),

that

you

rece

ive

sour

ceco

deor

can

geti

tif

you

wan

tit,

that

you

can

chan

geth

eso

ftw

are

orus

epi

eces

ofit

inne

wfr

eepr

ogra

ms,

and

that

you

know

you

can

doth

ese

thin

gs.

Topr

otec

tyou

rri

ghts

,we

need

topr

even

tot

hers

from

deny

ing

you

thes

eri

ghts

oras

king

you

tosu

rren

der

the

righ

ts.

The

re-

fore

,yo

uha

vece

rtai

nre

spon

si-

bilit

ies

ifyo

udi

stri

bute

copi

esof

the

soft

war

e,or

ifyo

um

od-

ify

it:re

spon

sibi

litie

sto

resp

ect

the

free

dom

ofot

hers

.

For

exam

ple,

ifyo

udi

stri

bute

copi

esof

such

apr

ogra

m,

whe

ther

grat

isor

for

afe

e,yo

um

ust

pass

onto

the

reci

pien

tsth

esa

me

free

dom

sth

atyo

ure

ceiv

ed.

You

mus

tm

ake

sure

353

Page 361: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

that

they

,too

,rec

eive

orca

nge

tth

eso

urce

code

.A

ndyo

um

ust

show

them

thes

ete

rms

soth

eykn

owth

eirr

ight

s.

Dev

elop

ers

that

use

the

GN

UG

PLpr

otec

tyo

urri

ghts

with

two

step

s:(1

)as

sert

copy

righ

ton

the

soft

war

e,an

d(2

)of

-fe

ryo

uth

isL

icen

segi

ving

you

lega

lpe

rmis

sion

toco

py,

dis-

trib

ute

and/

orm

odif

yit.

Fort

hede

velo

pers

’and

auth

ors’

prot

ectio

n,th

eG

PLcl

earl

yex

-pl

ains

that

ther

eis

now

arra

nty

for

this

free

soft

war

e.Fo

rbo

thus

ers’

and

auth

ors’

sake

,th

eG

PLre

quir

esth

atm

odifi

edve

r-si

ons

bem

arke

das

chan

ged,

soth

atth

eir

prob

lem

sw

illno

tbe

attr

ibut

eder

rone

ousl

yto

au-

thor

sof

prev

ious

vers

ions

.

Som

ede

vice

sar

ede

sign

edto

deny

user

sac

cess

toin

stal

lor

run

mod

ified

vers

ions

ofth

eso

ftw

are

insi

deth

em,

alth

ough

the

man

ufac

ture

rca

ndo

so.

Thi

sis

fund

amen

tally

inco

mpa

t-ib

lew

ithth

eai

mof

prot

ectin

gus

ers’

free

dom

toch

ange

the

soft

war

e.T

hesy

stem

atic

pat-

tern

ofsu

chab

use

occu

rsin

the

area

ofpr

oduc

tsfo

rin

divi

dual

sto

use,

whi

chis

prec

isel

yw

here

itis

mos

tun

acce

ptab

le.

The

re-

fore

,we

have

desi

gned

this

ver-

sion

ofth

eG

PLto

proh

ibit

the

prac

tice

for

thos

epr

oduc

ts.

Ifsu

chpr

oble

ms

aris

esu

bsta

n-tia

llyin

othe

rdom

ains

,we

stan

dre

ady

toex

tend

this

prov

isio

nto

thos

edo

mai

nsin

futu

reve

rsio

nsof

the

GPL

,as

need

edto

prot

ect

the

free

dom

ofus

ers.

Fina

lly,e

very

prog

ram

isth

reat

-en

edco

nsta

ntly

byso

ftw

are

pate

nts.

Stat

essh

ould

nota

llow

pate

nts

tore

stri

ctde

velo

pmen

tan

dus

eof

soft

war

eon

gene

ral-

purp

ose

com

pute

rs,b

utin

thos

eth

atdo

,w

ew

ish

toav

oid

the

spec

ial

dang

erth

atpa

tent

sap

-pl

ied

toa

free

prog

ram

coul

dm

ake

itef

fect

ivel

ypr

opri

etar

y.To

prev

entt

his,

the

GPL

assu

res

that

pate

nts

cann

otbe

used

tore

nder

the

prog

ram

non-

free

.

The

prec

ise

term

san

dco

n-di

tions

for

copy

ing,

dist

ribu

-tio

nan

dm

odifi

catio

nfo

llow

.T

ER

MS

AN

DC

ON

DIT

ION

S0.

Defi

nitio

ns.

“Thi

sL

icen

se”

refe

rsto

vers

ion

3of

the

GN

UG

ener

alPu

blic

Li-

cens

e.

“Cop

yrig

ht”

also

mea

nsco

pyri

ght-

like

law

sth

atap

-pl

yto

othe

rki

nds

ofw

orks

,su

chas

sem

icon

duct

orm

asks

.

“The

Prog

ram

”re

fers

toan

yco

pyri

ghta

ble

wor

klic

ense

dun

-de

rth

isL

icen

se.

Eac

hlic

ense

eis

addr

esse

das

“you

”.“L

i-ce

nsee

s”an

d“r

ecip

ient

s”m

aybe

indi

vidu

als

oror

gani

zatio

ns.

To“m

odif

y”a

wor

km

eans

toco

pyfr

omor

adap

tal

lor

part

ofth

ew

ork

ina

fash

ion

requ

ir-in

gco

pyri

ght

perm

issi

on,

othe

rth

anth

em

akin

gof

anex

act

copy

.T

here

sulti

ngw

ork

isca

lled

a“m

odifi

edve

rsio

n”of

the

earl

ier

wor

kor

aw

ork

“bas

edon

”th

eea

rlie

rwor

k.

A“c

over

edw

ork”

mea

nsei

ther

the

unm

odifi

edPr

ogra

mor

aw

ork

base

don

the

Prog

ram

.

To“p

ropa

gate

”a

wor

km

eans

todo

anyt

hing

with

itth

at,w

ithou

tpe

rmis

sion

,wou

ldm

ake

you

di-

rect

lyor

seco

ndar

ilylia

ble

for

infr

inge

men

tun

der

appl

icab

leco

pyri

ghtl

aw,e

xcep

texe

cutin

git

ona

com

pute

ror

mod

ify-

ing

apr

ivat

eco

py.

Prop

aga-

tion

incl

udes

copy

ing,

dist

ribu

-tio

n(w

ithor

with

out

mod

ifica

-tio

n),

mak

ing

avai

labl

eto

the

publ

ic,

and

inso

me

coun

trie

sot

hera

ctiv

ities

asw

ell.

To“c

onve

y”a

wor

km

eans

any

kind

ofpr

opag

atio

nth

aten

able

sot

her

part

ies

tom

ake

orre

ceiv

eco

pies

.M

ere

inte

ract

ion

with

aus

erth

roug

ha

com

pute

rne

t-w

ork,

with

notr

ansf

erof

aco

py,

isno

tcon

veyi

ng.

An

inte

ract

ive

user

inte

rfac

edi

s-pl

ays

“App

ropr

iate

Leg

alN

o-tic

es”

toth

eex

tent

that

itin

-cl

udes

aco

nven

ient

and

prom

i-ne

ntly

visi

ble

feat

ure

that

(1)

disp

lays

anap

prop

riat

eco

py-

righ

tno

tice,

and

(2)

tells

the

user

that

ther

eis

now

arra

nty

for

the

wor

k(e

xcep

tto

the

exte

ntth

atw

arra

ntie

sar

epr

ovid

ed),

that

licen

sees

may

conv

eyth

ew

ork

unde

rth

isL

icen

se,

and

how

tovi

ewa

copy

ofth

isL

i-ce

nse.

Ifth

ein

terf

ace

pres

ents

alis

tof

user

com

man

dsor

op-

tions

,suc

has

am

enu,

apr

omi-

Page 362: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

nent

item

inth

elis

tm

eets

this

crite

rion

.1.S

ourc

eC

ode.

The

“sou

rce

code

”fo

ra

wor

km

eans

the

pref

erre

dfo

rmof

the

wor

kfo

rm

akin

gm

odifi

catio

nsto

it.“O

bjec

tco

de”

mea

nsan

yno

n-so

urce

form

ofa

wor

k.

A“S

tand

ard

Inte

rfac

e”m

eans

anin

terf

ace

that

eith

eris

anof

fi-ci

alst

anda

rdde

fined

bya

reco

g-ni

zed

stan

dard

sbo

dy,o

r,in

the

case

ofin

terf

aces

spec

ified

for

apa

rtic

ular

prog

ram

min

gla

n-gu

age,

one

that

isw

idel

yus

edam

ong

deve

lope

rsw

orki

ngin

that

lang

uage

.

The

“Sys

tem

Lib

rari

es”

ofan

ex-

ecut

able

wor

kin

clud

ean

ythi

ng,

othe

rth

anth

ew

ork

asa

who

le,

that

(a)

isin

clud

edin

the

nor-

mal

form

ofpa

ckag

ing

aM

a-jo

rCom

pone

nt,b

utw

hich

isno

tpa

rtof

that

Maj

orC

ompo

nent

,an

d(b

)se

rves

only

toen

able

use

ofth

ew

ork

with

that

Maj

orC

ompo

nent

,or

toim

plem

ent

aSt

anda

rdIn

terf

ace

for

whi

chan

impl

emen

tatio

nis

avai

labl

eto

the

publ

icin

sour

ceco

defo

rm.

A“M

ajor

Com

pone

nt”,

inth

isco

ntex

t,m

eans

am

ajor

esse

n-

tialc

ompo

nent

(ker

nel,

win

dow

syst

em,

and

soon

)of

the

spe-

cific

oper

atin

gsy

stem

(if

any)

onw

hich

the

exec

utab

lew

ork

runs

,or

aco

mpi

ler

used

topr

o-du

ceth

ew

ork,

oran

obje

ctco

dein

terp

rete

ruse

dto

run

it.

The

“Cor

resp

ondi

ngSo

urce

”fo

ra

wor

kin

obje

ctco

defo

rmm

eans

all

the

sour

ceco

dene

eded

toge

nera

te,

inst

all,

and

(for

anex

ecut

able

wor

k)ru

nth

eob

ject

code

and

tom

odif

yth

ew

ork,

incl

udin

gsc

ript

sto

con-

trol

thos

eac

tiviti

es.

How

ever

,it

does

not

incl

ude

the

wor

k’s

Syst

emL

ibra

ries

,or

gene

ral-

purp

ose

tool

sor

gene

rally

avai

labl

efr

eepr

ogra

ms

whi

char

eus

edun

mod

ified

inpe

rfor

m-

ing

thos

eac

tiviti

esbu

tw

hich

are

not

part

ofth

ew

ork.

For

exam

ple,

Cor

resp

ondi

ngSo

urce

incl

udes

inte

rfac

ede

finiti

onfil

esas

soci

ated

with

sour

cefil

esfo

rth

ew

ork,

and

the

sour

ceco

defo

rsha

red

libra

ries

and

dy-

nam

ical

lylin

ked

subp

rogr

ams

that

the

wor

kis

spec

ifica

llyde

sign

edto

requ

ire,

such

asby

intim

ate

data

com

mun

icat

ion

orco

ntro

lflo

wbe

twee

nth

ose

subp

rogr

ams

and

othe

rpa

rts

ofth

ew

ork.

The

Cor

resp

ondi

ngSo

urce

need

not

incl

ude

anyt

hing

that

user

sca

nre

gene

rate

auto

mat

-ic

ally

from

othe

rpa

rts

ofth

eC

orre

spon

ding

Sour

ce.

The

Cor

resp

ondi

ngSo

urce

fora

wor

kin

sour

ceco

defo

rmis

that

sam

ew

ork.

2.B

asic

Perm

is-

sion

s.

All

righ

tsgr

ante

dun

der

this

Li-

cens

ear

egr

ante

dfo

rth

ete

rmof

copy

righ

ton

the

Prog

ram

,an

dar

eir

revo

cabl

epr

ovid

edth

est

ated

cond

ition

sar

em

et.

Thi

sL

icen

seex

plic

itly

affir

ms

your

unlim

ited

perm

issi

onto

run

the

unm

odifi

edPr

ogra

m.

The

out-

put

from

runn

ing

aco

vere

dw

ork

isco

vere

dby

this

Lic

ense

only

ifth

eou

tput

,gi

ven

itsco

nten

t,co

nstit

utes

aco

vere

dw

ork.

Thi

sL

icen

seac

know

l-ed

ges

your

righ

tsof

fair

use

orot

here

quiv

alen

t,as

prov

ided

byco

pyri

ghtl

aw.

You

may

mak

e,ru

nan

dpr

opa-

gate

cove

red

wor

ksth

atyo

udo

not

conv

ey,

with

out

cond

ition

s

solo

ngas

your

licen

seot

her-

wis

ere

mai

nsin

forc

e.Y

oum

ayco

nvey

cove

red

wor

ksto

othe

rsfo

rth

eso

lepu

rpos

eof

havi

ngth

emm

ake

mod

ifica

tions

excl

u-si

vely

for

you,

orpr

ovid

eyo

uw

ithfa

cilit

ies

for

runn

ing

thos

ew

orks

,pr

ovid

edth

atyo

uco

m-

ply

with

the

term

sof

this

Li-

cens

ein

conv

eyin

gal

lm

ater

ial

for

whi

chyo

udo

not

cont

rol

copy

righ

t.T

hose

thus

mak

ing

orru

nnin

gth

eco

vere

dw

orks

for

you

mus

tdo

soex

clus

ivel

yon

your

beha

lf,

unde

ryo

urdi

-re

ctio

nan

dco

ntro

l,on

term

sth

atpr

ohib

itth

emfr

omm

akin

gan

yco

pies

ofyo

urco

pyri

ghte

dm

ater

ial

outs

ide

thei

rre

latio

n-sh

ipw

ithyo

u.

Con

veyi

ngun

der

any

othe

rci

r-cu

mst

ance

sis

perm

itted

sole

lyun

der

the

cond

ition

sst

ated

be-

low

.Su

blic

ensi

ngis

not

al-

low

ed;

sect

ion

10m

akes

itun

nece

ssar

y.3.

Prot

ectin

gU

sers

’L

egal

Rig

hts

From

Ant

i-C

ircu

mve

ntio

nL

aw.

No

cove

red

wor

ksh

all

bede

emed

part

ofan

effe

ctiv

ete

ch-

nolo

gica

lmea

sure

unde

rany

ap-

plic

able

law

fulfi

lling

oblig

a-

Page 363: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

tions

unde

rar

ticle

11of

the

WIP

Oco

pyri

ght

trea

tyad

opte

don

20D

ecem

ber

1996

,or

sim

-ila

rla

ws

proh

ibiti

ngor

rest

rict

-in

gci

rcum

vent

ion

ofsu

chm

ea-

sure

s.

Whe

nyo

uco

nvey

aco

vere

dw

ork,

you

wai

vean

yle

gal

pow

erto

forb

idci

rcum

vent

ion

ofte

chno

logi

calm

easu

res

toth

eex

tent

such

circ

umve

ntio

nis

ef-

fect

edby

exer

cisi

ngri

ghts

un-

der

this

Lic

ense

with

resp

ectt

oth

eco

vere

dw

ork,

and

you

dis-

clai

man

yin

tent

ion

tolim

itop

-er

atio

nor

mod

ifica

tion

ofth

ew

ork

asa

mea

nsof

enfo

rcin

g,ag

ains

tthe

wor

k’s

user

s,yo

uror

thir

dpa

rtie

s’le

gal

righ

tsto

for-

bid

circ

umve

ntio

nof

tech

nolo

g-ic

alm

easu

res.

4.C

onve

ying

Ver

batim

Cop

ies.

You

may

conv

eyve

rbat

imco

pies

ofth

ePr

ogra

m’s

sour

ceco

deas

you

rece

ive

it,in

any

med

ium

,pro

vide

dth

atyo

uco

n-sp

icuo

usly

and

appr

opri

atel

ypu

blis

hon

each

copy

anap

pro-

pria

teco

pyri

ght

notic

e;ke

epin

tact

alln

otic

esst

atin

gth

atth

isL

icen

sean

dan

yno

n-pe

rmis

sive

term

sad

ded

inac

cord

with

sec-

tion

7ap

ply

toth

eco

de;

keep

inta

ctal

lnot

ices

ofth

eab

senc

eof

any

war

rant

y;an

dgi

veal

lre

cipi

ents

aco

pyof

this

Lic

ense

alon

gw

ithth

ePr

ogra

m.

You

may

char

gean

ypr

ice

orno

pric

efo

reac

hco

pyth

atyo

uco

n-ve

y,an

dyo

um

ayof

fer

supp

ort

orw

arra

nty

prot

ectio

nfo

ra

fee.

5.C

onve

ying

Mod

ified

Sour

ceV

ersi

ons.

You

may

conv

eya

wor

kba

sed

onth

ePr

ogra

m,o

rthe

mod

ifica

-tio

nsto

prod

uce

itfr

omth

ePr

o-gr

am,i

nth

efo

rmof

sour

ceco

deun

dert

hete

rmso

fsec

tion

4,pr

o-vi

ded

that

you

also

mee

tal

lof

thes

eco

nditi

ons:

*a)

The

wor

km

ustc

arry

prom

i-ne

ntno

tices

stat

ing

that

you

mod

ified

it,an

dgi

ving

are

le-

vant

date

.*

b)T

hew

ork

mus

tca

rry

prom

inen

tno

tices

stat

ing

that

itis

rele

ased

unde

rth

isL

i-ce

nse

and

any

cond

ition

sad

ded

unde

rse

ctio

n7.

Thi

sre

quir

e-m

ent

mod

ifies

the

requ

irem

ent

inse

ctio

n4

to“k

eep

inta

ctal

lno

tices

”.*

c)Y

oum

ustl

icen

seth

een

tire

wor

k,as

aw

hole

,un-

der

this

Lic

ense

toan

yone

who

com

esin

topo

sses

sion

ofa

copy

.T

his

Lic

ense

will

ther

efor

eap

-pl

y,al

ong

with

any

appl

icab

lese

ctio

n7

addi

tiona

lte

rms,

toth

ew

hole

ofth

ew

ork,

and

all

itspa

rts,

rega

rdle

ssof

how

they

are

pack

aged

.T

his

Lic

ense

give

sno

perm

issi

onto

licen

seth

ew

ork

inan

yot

her

way

,bu

tit

does

not

inva

lidat

esu

chpe

r-m

issi

onif

you

have

sepa

rate

lyre

ceiv

edit.

*d)

Ifth

ew

ork

has

inte

ract

ive

user

inte

rfac

es,e

ach

mus

tdis

play

App

ropr

iate

Leg

alN

otic

es;

how

ever

,if

the

Pro-

gram

has

inte

ract

ive

inte

rfac

esth

atdo

not

disp

lay

App

ropr

iate

Leg

alN

otic

es,

your

wor

kne

edno

tmak

eth

emdo

so.

Aco

mpi

latio

nof

aco

vere

dw

ork

with

othe

rsep

arat

ean

din

-de

pend

entw

orks

,whi

char

eno

tby

thei

rnat

ure

exte

nsio

nsof

the

cove

red

wor

k,an

dw

hich

are

notc

ombi

ned

with

itsu

chas

tofo

rma

larg

erpr

ogra

m,i

nor

ona

volu

me

ofa

stor

age

ordi

stri

-bu

tion

med

ium

,is

calle

dan

“ag-

greg

ate”

ifth

eco

mpi

latio

nan

dits

resu

lting

copy

righ

tar

eno

tus

edto

limit

the

acce

ssor

le-

gal

righ

tsof

the

com

pila

tion’

sus

ers

beyo

ndw

hat

the

indi

vid-

ual

wor

kspe

rmit.

Incl

usio

nof

aco

vere

dw

ork

inan

aggr

egat

edo

esno

tca

use

this

Lic

ense

toap

ply

toth

eot

her

part

sof

the

aggr

egat

e.6.

Con

veyi

ngN

on-

Sour

ceFo

rms.

You

may

conv

eya

cove

red

wor

kin

obje

ctco

defo

rmun

-de

rth

ete

rms

ofse

ctio

ns4

and

5,pr

ovid

edth

atyo

ual

soco

n-ve

yth

em

achi

ne-r

eada

ble

Cor

-re

spon

ding

Sour

ceun

der

the

term

sof

this

Lic

ense

,in

one

ofth

ese

way

s:

*a)

Con

vey

the

obje

ctco

dein

,or

embo

died

in,

aph

ysic

alpr

oduc

t(i

nclu

ding

aph

ysic

aldi

stri

butio

nm

ediu

m),

acco

m-

pani

edby

the

Cor

resp

ondi

ngSo

urce

fixed

ona

dura

ble

phys

-ic

alm

ediu

mcu

stom

arily

used

for

soft

war

ein

terc

hang

e.*

b)C

onve

yth

eob

ject

code

in,

orem

bodi

edin

,a

phys

ical

prod

-uc

t(i

nclu

ding

aph

ysic

aldi

stri

-bu

tion

med

ium

),ac

com

pani

edby

aw

ritte

nof

fer,

valid

for

atle

astt

hree

year

san

dva

lidfo

ras

long

asyo

uof

fer

spar

epa

rts

orcu

stom

ersu

ppor

tfo

rth

atpr

od-

uct

mod

el,

togi

vean

yone

who

poss

esse

sth

eob

ject

code

eith

er

Page 364: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

(1)

aco

pyof

the

Cor

resp

ond-

ing

Sour

cefo

ral

lth

eso

ftw

are

inth

epr

oduc

ttha

tis

cove

red

byth

isL

icen

se,o

na

dura

ble

phys

-ic

alm

ediu

mcu

stom

arily

used

for

soft

war

ein

terc

hang

e,fo

ra

pric

eno

mor

eth

anyo

urre

ason

-ab

leco

stof

phys

ical

lype

rfor

m-

ing

this

conv

eyin

gof

sour

ce,

or(2

)ac

cess

toco

pyth

eC

or-

resp

ondi

ngSo

urce

from

ane

t-w

ork

serv

erat

noch

arge

.*

c)C

onve

yin

divi

dual

copi

esof

the

obje

ctco

dew

itha

copy

ofth

ew

ritte

nof

fer

topr

ovid

eth

eC

or-

resp

ondi

ngSo

urce

.Thi

salte

rna-

tive

isal

low

edon

lyoc

casi

onal

lyan

dno

ncom

mer

cial

ly,a

ndon

lyif

you

rece

ived

the

obje

ctco

dew

ithsu

chan

offe

r,in

acco

rdw

ithsu

bsec

tion

6b.

*d)

Con

-ve

yth

eob

ject

code

byof

feri

ngac

cess

from

ade

sign

ated

plac

e(g

ratis

orfo

ra

char

ge),

and

of-

fer

equi

vale

ntac

cess

toth

eC

or-

resp

ondi

ngSo

urce

inth

esa

me

way

thro

ugh

the

sam

epl

ace

atno

furt

her

char

ge.

You

need

not

requ

ire

reci

pien

tsto

copy

the

Cor

resp

ondi

ngSo

urce

alon

gw

ithth

eob

ject

code

.Ift

hepl

ace

toco

pyth

eob

ject

code

isa

netw

ork

serv

er,t

heC

orre

spon

d-in

gSo

urce

may

beon

adi

ffer

-

ents

erve

r(op

erat

edby

you

ora

thir

dpa

rty)

that

supp

orts

equi

va-

lent

copy

ing

faci

litie

s,pr

ovid

edyo

um

aint

ain

clea

rdi

rect

ions

next

toth

eob

ject

code

sayi

ngw

here

tofin

dth

eC

orre

spon

d-in

gSo

urce

.R

egar

dles

sof

wha

tse

rver

host

sth

eC

orre

spon

ding

Sour

ce,

you

rem

ain

oblig

ated

toen

sure

that

itis

avai

labl

efo

ras

long

asne

eded

tosa

tisfy

thes

ere

quir

emen

ts.

*e)

Con

-ve

yth

eob

ject

code

usin

gpe

er-

to-p

eer

tran

smis

sion

,pr

ovid

edyo

uin

form

othe

rpe

ers

whe

reth

eob

ject

code

and

Cor

resp

ond-

ing

Sour

ceof

the

wor

kar

ebe

ing

offe

red

toth

ege

nera

lpu

blic

atno

char

geun

ders

ubse

ctio

n6d

.

Ase

para

ble

port

ion

ofth

eob

-je

ctco

de,w

hose

sour

ceco

deis

excl

uded

from

the

Cor

resp

ond-

ing

Sour

ceas

aSy

stem

Lib

rary

,ne

edno

tbe

incl

uded

inco

nvey

-in

gth

eob

ject

code

wor

k.

A“U

ser

Prod

uct”

isei

ther

(1)

a“c

onsu

mer

prod

uct”

,w

hich

mea

nsan

yta

ngib

lepe

rson

alpr

oper

tyw

hich

isno

rmal

lyus

edfo

rpe

rson

al,

fam

ily,

orho

use-

hold

purp

oses

,or

(2)

anyt

hing

desi

gned

orso

ldfo

rin

corp

ora-

tion

into

adw

ellin

g.In

de-

term

inin

gw

heth

era

prod

uct

isa

cons

umer

prod

uct,

doub

tful

case

ssh

all

bere

solv

edin

favo

rof

cove

rage

.Fo

ra

part

icul

arpr

oduc

tre

ceiv

edby

apa

rtic

u-la

rus

er,“

norm

ally

used

”re

fers

toa

typi

cal

orco

mm

onus

eof

that

clas

sof

prod

uct,

rega

rdle

ssof

the

stat

usof

the

part

icul

arus

eror

ofth

ew

ayin

whi

chth

epa

rtic

ular

user

actu

ally

uses

,or

expe

cts

oris

expe

cted

tous

e,th

epr

oduc

t.A

prod

uct

isa

cons

umer

prod

uct

rega

rdle

ssof

whe

ther

the

prod

ucth

assu

bsta

n-tia

lco

mm

erci

al,

indu

stri

alor

non-

cons

umer

uses

,unl

ess

such

uses

repr

esen

tth

eon

lysi

gnifi

-ca

ntm

ode

ofus

eof

the

prod

uct.

“Ins

talla

tion

Info

rmat

ion”

for

aU

ser

Prod

uct

mea

nsan

ym

eth-

ods,

proc

edur

es,

auth

oriz

atio

nke

ys,

orot

her

info

rmat

ion

re-

quir

edto

inst

all

and

exec

ute

mod

ified

vers

ions

ofa

cove

red

wor

kin

that

Use

rPr

oduc

tfro

ma

mod

ified

vers

ion

ofits

Cor

-re

spon

ding

Sour

ce.

The

info

r-m

atio

nm

ust

suffi

ceto

ensu

reth

atth

eco

ntin

ued

func

tioni

ngof

the

mod

ified

obje

ctco

deis

inno

case

prev

ente

dor

inte

r-

fere

dw

ithso

lely

beca

use

mod

-ifi

catio

nha

sbe

enm

ade.

Ifyo

uco

nvey

anob

ject

code

wor

kun

der

this

sect

ion

in,

orw

ith,

orsp

ecifi

cally

for

use

in,

aU

ser

Prod

uct,

and

the

conv

ey-

ing

occu

rsas

part

ofa

tran

sac-

tion

inw

hich

the

righ

tofp

osse

s-si

onan

dus

eof

the

Use

rPr

od-

ucti

str

ansf

erre

dto

the

reci

pien

tin

perp

etui

tyor

for

afix

edte

rm(r

egar

dles

sof

how

the

tran

sac-

tion

isch

arac

teri

zed)

,th

eC

or-

resp

ondi

ngSo

urce

conv

eyed

un-

der

this

sect

ion

mus

tbe

acco

m-

pani

edby

the

Inst

alla

tion

Info

r-m

atio

n.B

utth

isre

quir

emen

tdo

esno

tapp

lyif

neith

eryo

uno

ran

yth

ird

part

yre

tain

sthe

abili

tyto

inst

all

mod

ified

obje

ctco

deon

the

Use

rPr

oduc

t(f

orex

am-

ple,

the

wor

kha

sbe

enin

stal

led

inR

OM

).

The

requ

irem

ent

topr

ovid

eIn

-st

alla

tion

Info

rmat

ion

does

not

incl

ude

are

quir

emen

tto

con-

tinue

topr

ovid

esu

ppor

tser

vice

,w

arra

nty,

orup

date

sfo

ra

wor

kth

atha

sbe

enm

odifi

edor

in-

stal

led

byth

ere

cipi

ent,

orfo

rth

eU

serP

rodu

ctin

whi

chit

has

been

mod

ified

orin

stal

led.

Ac-

Page 365: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

cess

toa

netw

ork

may

bede

nied

whe

nth

em

odifi

catio

nits

elfm

a-te

rial

lyan

dad

vers

ely

affe

ctst

heop

erat

ion

ofth

ene

twor

kor

vio-

late

sth

eru

les

and

prot

ocol

sfo

rco

mm

unic

atio

nac

ross

the

net-

wor

k.

Cor

resp

ondi

ngSo

urce

con-

veye

d,an

dIn

stal

latio

nIn

form

a-tio

npr

ovid

ed,

inac

cord

with

this

sect

ion

mus

tbe

ina

form

atth

atis

publ

icly

docu

men

ted

(and

with

anim

plem

enta

tion

avai

labl

eto

the

publ

icin

sour

ceco

defo

rm),

and

mus

tre

quir

eno

spec

ial

pass

wor

dor

key

for

unpa

ckin

g,re

adin

gor

copy

ing.

7.A

dditi

onal

Term

s.

“Add

ition

alpe

rmis

sion

s”ar

ete

rms

that

supp

lem

entt

hete

rms

ofth

isL

icen

seby

mak

ing

exce

ptio

nsfr

omon

eor

mor

eof

itsco

nditi

ons.

Add

ition

alpe

rmis

sion

sth

atar

eap

plic

able

toth

een

tire

Prog

ram

shal

lbe

trea

ted

asth

ough

they

wer

ein

clud

edin

this

Lic

ense

,to

the

exte

ntth

atth

eyar

eva

lidun

der

appl

icab

lela

w.

Ifad

ditio

nal

perm

issi

ons

appl

yon

lyto

part

ofth

ePr

ogra

m,

that

part

may

beus

edse

para

tely

unde

rth

ose

perm

issi

ons,

but

the

entir

ePr

ogra

mre

mai

nsgo

vern

edby

this

Lic

ense

with

out

rega

rdto

the

addi

tiona

lper

mis

sion

s.

Whe

nyo

uco

nvey

aco

pyof

aco

vere

dw

ork,

you

may

atyo

urop

tion

rem

ove

any

addi

tiona

lpe

rmis

sion

sfr

omth

atco

py,

orfr

oman

ypa

rtof

it.(A

ddi-

tiona

lpe

rmis

sion

sm

aybe

wri

t-te

nto

requ

ire

thei

row

nre

mov

alin

cert

ain

case

sw

hen

you

mod

-if

yth

ew

ork.

)Y

oum

aypl

ace

addi

tiona

lper

mis

sion

son

mat

e-ri

al,a

dded

byyo

uto

aco

vere

dw

ork,

forw

hich

you

have

orca

ngi

veap

prop

riat

eco

pyri

ght

per-

mis

sion

.

Not

with

stan

ding

any

othe

rpr

o-vi

sion

ofth

isL

icen

se,f

orm

ate-

rial

you

add

toa

cove

red

wor

k,yo

um

ay(i

fau

thor

ized

byth

eco

pyri

ght

hold

ers

ofth

atm

ate-

rial

)su

pple

men

tth

ete

rms

ofth

isL

icen

sew

ithte

rms:

*a)

Dis

clai

min

gw

arra

nty

orlim

iting

liabi

lity

diff

eren

tlyfr

omth

ete

rms

ofse

ctio

ns15

and

16of

this

Lic

ense

;or

*b)

Req

uiri

ngpr

eser

vatio

nof

spec

-ifi

edre

ason

able

lega

lno

tices

orau

thor

attr

ibut

ions

inth

atm

ater

ial

orin

the

App

ropr

iate

Leg

alN

otic

esdi

spla

yed

byw

orks

cont

aini

ngit;

or*

c)Pr

ohib

iting

mis

repr

esen

tatio

nof

the

orig

inof

that

mat

eria

l,or

requ

irin

gth

atm

odifi

edve

rsio

nsof

such

mat

eria

lbe

mar

ked

inre

ason

able

way

sas

diff

eren

tfr

omth

eor

igin

alve

rsio

n;or

*d)

Lim

iting

the

use

forp

ublic

itypu

rpos

esof

nam

esof

licen

sors

orau

thor

sof

the

mat

eria

l;or

*e)

Dec

linin

gto

gran

tri

ghts

unde

rtr

adem

ark

law

for

use

ofso

me

trad

ena

mes

,tr

adem

arks

,or

serv

ice

mar

ks;o

r*f)

Req

uir-

ing

inde

mni

ficat

ion

oflic

enso

rsan

dau

thor

sof

that

mat

eria

lby

anyo

new

hoco

nvey

sth

em

ate-

rial

(or

mod

ified

vers

ions

ofit)

with

cont

ract

uala

ssum

ptio

nsof

liabi

lity

toth

ere

cipi

ent,

for

any

liabi

lity

that

thes

eco

ntra

ctua

las

sum

ptio

nsdi

rect

lyim

pose

onth

ose

licen

sors

and

auth

ors.

All

othe

rno

n-pe

rmis

sive

ad-

ditio

nal

term

sar

eco

nsid

ered

“fur

ther

rest

rict

ions

”w

ithin

the

mea

ning

ofse

ctio

n10

.If

the

Prog

ram

asyo

ure

ceiv

edit,

oran

ypa

rtof

it,co

ntai

nsa

notic

est

atin

gth

atit

isgo

vern

edby

this

Lic

ense

alon

gw

itha

term

that

isa

furt

her

rest

rict

ion,

you

may

rem

ove

that

term

.If

alic

ense

docu

men

tco

ntai

nsa

furt

her

re-

stri

ctio

nbu

tper

mits

relic

ensi

ngor

conv

eyin

gun

dert

his

Lic

ense

,yo

um

ayad

dto

aco

vere

dw

ork

mat

eria

lgo

vern

edby

the

term

sof

that

licen

sedo

cum

ent,

pro-

vide

dth

atth

efu

rthe

rre

stri

ctio

ndo

esno

tsu

rviv

esu

chre

licen

s-in

gor

conv

eyin

g.

Ifyo

uad

dte

rms

toa

cove

red

wor

kin

acco

rdw

ithth

isse

ctio

n,yo

um

ust

plac

e,in

the

rele

vant

sour

cefil

es,

ast

atem

ent

ofth

ead

ditio

nal

term

sth

atap

ply

toth

ose

files

,or

ano

tice

indi

cat-

ing

whe

reto

find

the

appl

icab

lete

rms.

Add

ition

alte

rms,

perm

issi

veor

non-

perm

issi

ve,

may

best

ated

inth

efo

rmof

ase

para

tely

wri

t-te

nlic

ense

,or

stat

edas

exce

p-tio

ns;

the

abov

ere

quir

emen

tsap

ply

eith

erw

ay.

8.Te

rmin

a-tio

n.

You

may

notp

ropa

gate

orm

od-

ify

aco

vere

dw

ork

exce

ptas

ex-

pres

sly

prov

ided

unde

rth

isL

i-ce

nse.

Any

atte

mpt

othe

rwis

e

Page 366: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

topr

opag

ate

orm

odif

yit

isvo

id,a

ndw

illau

tom

atic

ally

ter-

min

ate

your

righ

tsun

dert

his

Li-

cens

e(i

nclu

ding

any

pate

ntli-

cens

esgr

ante

dun

der

the

thir

dpa

ragr

aph

ofse

ctio

n11

).

How

ever

,if

you

ceas

eal

lvio

la-

tion

ofth

isL

icen

se,

then

your

licen

sefr

oma

part

icul

arco

py-

righ

thol

deri

sre

inst

ated

(a)p

ro-

visi

onal

ly,

unle

ssan

dun

tilth

eco

pyri

ght

hold

erex

plic

itly

and

final

lyte

rmin

ates

your

licen

se,

and

(b)p

erm

anen

tly,i

fthe

copy

-ri

ght

hold

erfa

ilsto

notif

yyo

uof

the

viol

atio

nby

som

ere

ason

-ab

lem

eans

prio

rto

60da

ysaf

ter

the

cess

atio

n.

Mor

eove

r,yo

urlic

ense

from

apa

rtic

ular

copy

righ

thol

deri

sre

-in

stat

edpe

rman

ently

ifth

eco

py-

righ

tho

lder

notifi

esyo

uof

the

viol

atio

nby

som

ere

ason

able

mea

ns,t

his

isth

efir

sttim

eyo

uha

vere

ceiv

edno

tice

ofvi

olat

ion

ofth

isL

icen

se(f

oran

yw

ork)

from

that

copy

righ

tho

lder

,and

you

cure

the

viol

atio

npr

ior

to30

days

afte

ryou

rrec

eipt

ofth

eno

tice.

Term

inat

ion

ofyo

urri

ghts

unde

rth

isse

ctio

ndo

esno

tte

rmin

ate

the

licen

ses

ofpa

rtie

sw

hoha

vere

ceiv

edco

pies

orri

ghts

from

you

unde

rth

isL

icen

se.

Ifyo

urri

ghts

have

been

term

inat

edan

dno

tper

man

ently

rein

stat

ed,y

oudo

not

qual

ify

tore

ceiv

ene

wlic

ense

sfo

rth

esa

me

mat

eria

lun

der

sect

ion

10.

9.A

ccep

-ta

nce

Not

Req

uire

dfo

rH

avin

gC

opie

s.

You

are

not

requ

ired

toac

-ce

ptth

isL

icen

sein

orde

rto

rece

ive

orru

na

copy

ofth

ePr

ogra

m.

Anc

illar

ypr

opag

a-tio

nof

aco

vere

dw

ork

occu

r-ri

ngso

lely

asa

cons

eque

nce

ofus

ing

peer

-to-

peer

tran

smis

sion

tore

ceiv

ea

copy

likew

ise

does

not

requ

ire

acce

ptan

ce.

How

-ev

er,n

othi

ngot

her

than

this

Li-

cens

egr

ants

you

perm

issi

onto

prop

agat

eor

mod

ify

any

cov-

ered

wor

k.T

hese

actio

nsin

-fr

inge

copy

righ

tif

you

dono

tac

cept

this

Lic

ense

.T

here

fore

,by

mod

ifyi

ngor

prop

agat

ing

aco

vere

dw

ork,

you

indi

cate

your

acce

ptan

ceof

this

Lic

ense

todo

so.

10.

Aut

omat

icL

icen

sing

ofD

owns

trea

mR

ecip

ient

s.

Eac

htim

eyo

uco

nvey

aco

vere

dw

ork,

the

reci

pien

tau

tom

ati-

cally

rece

ives

alic

ense

from

the

orig

inal

licen

sors

,to

run,

mod

-if

yan

dpr

opag

ate

that

wor

k,su

b-je

ctto

this

Lic

ense

.You

are

not

resp

onsi

ble

for

enfo

rcin

gco

m-

plia

nce

byth

ird

part

ies

with

this

Lic

ense

.

An

“ent

itytr

ansa

ctio

n”is

atr

ansa

ctio

ntr

ansf

erri

ngco

ntro

lof

anor

gani

zatio

n,or

subs

tan-

tially

alla

sset

sof

one,

orsu

bdi-

vidi

ngan

orga

niza

tion,

orm

erg-

ing

orga

niza

tions

.If

prop

aga-

tion

ofa

cove

red

wor

kre

sults

from

anen

tity

tran

sact

ion,

each

part

yto

that

tran

sact

ion

who

re-

ceiv

esa

copy

ofth

ew

ork

also

rece

ives

wha

teve

rlic

ense

sto

the

wor

kth

epa

rty’

spr

edec

esso

rin

inte

rest

had

orco

uld

give

unde

rth

epr

evio

uspa

ragr

aph,

plus

ari

ght

topo

sses

sion

ofth

eC

or-

resp

ondi

ngSo

urce

ofth

ew

ork

from

the

pred

eces

sori

nin

tere

st,

ifth

epr

edec

esso

rha

sit

orca

nge

titw

ithre

ason

able

effo

rts.

You

may

not

impo

sean

yfu

r-th

erre

stri

ctio

nson

the

exer

cise

ofth

eri

ghts

gran

ted

oraf

firm

edun

der

this

Lic

ense

.Fo

rex

-

ampl

e,yo

um

ayno

tim

pose

alic

ense

fee,

roya

lty,

orot

her

char

gefo

rex

erci

seof

righ

tsgr

ante

dun

der

this

Lic

ense

,and

you

may

not

initi

ate

litig

a-tio

n(i

nclu

ding

acr

oss-

clai

mor

coun

terc

laim

ina

law

suit)

alle

g-in

gth

atan

ypa

tent

clai

mis

in-

frin

ged

bym

akin

g,us

ing,

sell-

ing,

offe

ring

for

sale

,or

impo

rt-

ing

the

Prog

ram

oran

ypo

rtio

nof

it.11

.Pat

ents

.

A“c

ontr

ibut

or”

isa

copy

righ

tho

lder

who

auth

oriz

esus

eun

der

this

Lic

ense

ofth

ePr

ogra

mor

aw

ork

onw

hich

the

Prog

ram

isba

sed.

The

wor

kth

uslic

ense

dis

calle

dth

eco

ntri

buto

r’s

“con

-tr

ibut

orve

rsio

n”.

Aco

ntri

buto

r’s

“ess

entia

lpat

ent

clai

ms”

are

all

pate

ntcl

aim

sow

ned

orco

ntro

lled

byth

eco

n-tr

ibut

or,

whe

ther

alre

ady

ac-

quir

edor

here

afte

rac

quir

ed,

that

wou

ldbe

infr

inge

dby

som

em

anne

r,pe

rmitt

edby

this

Li-

cens

e,of

mak

ing,

usin

g,or

sell-

ing

itsco

ntri

buto

rve

rsio

n,bu

tdo

noti

nclu

decl

aim

stha

twou

ldbe

infr

inge

don

lyas

aco

nse-

quen

ceof

furt

her

mod

ifica

tion

ofth

eco

ntri

buto

rve

rsio

n.Fo

r

Page 367: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

purp

oses

ofth

isde

finiti

on,“

con-

trol

”in

clud

esth

eri

ght

togr

ant

pate

ntsu

blic

ense

sin

am

anne

rco

nsis

tent

with

the

requ

irem

ents

ofth

isL

icen

se.

Eac

hco

ntri

buto

rgr

ants

you

ano

n-ex

clus

ive,

wor

ldw

ide,

roya

lty-f

ree

pate

ntlic

ense

un-

der

the

cont

ribu

tor’

ses

sent

ial

pate

ntcl

aim

s,to

mak

e,us

e,se

ll,of

fer

for

sale

,im

port

and

othe

r-w

ise

run,

mod

ify

and

prop

agat

eth

eco

nten

tsof

itsco

ntri

buto

rve

rsio

n.

Inth

efo

llow

ing

thre

epa

ra-

grap

hs,

a“p

aten

tlic

ense

”is

any

expr

ess

agre

emen

tor

com

-m

itmen

t,ho

wev

erde

nom

inat

ed,

nott

oen

forc

ea

pate

nt(s

uch

asan

expr

ess

perm

issi

onto

prac

-tic

ea

pate

ntor

cove

nant

not

tosu

efo

rpat

enti

nfri

ngem

ent)

.To

“gra

nt”

such

apa

tent

licen

seto

apa

rty

mea

nsto

mak

esu

chan

agre

emen

tor

com

mitm

ent

not

toen

forc

ea

pate

ntag

ains

tth

epa

rty.

Ifyo

uco

nvey

aco

vere

dw

ork,

know

ingl

yre

lyin

gon

apa

tent

licen

se,

and

the

Cor

resp

ondi

ngSo

urce

ofth

ew

ork

isno

tava

il-

able

for

anyo

neto

copy

,fr

eeof

char

gean

dun

der

the

term

sof

this

Lic

ense

,th

roug

ha

pub-

licly

avai

labl

ene

twor

kse

rver

orot

her

read

ilyac

cess

ible

mea

ns,

then

you

mus

tei

ther

(1)

caus

eth

eC

orre

spon

ding

Sour

ceto

beso

avai

labl

e,or

(2)

arra

nge

tode

priv

eyo

urse

lfof

the

bene

fitof

the

pate

ntlic

ense

for

this

part

icul

arw

ork,

or(3

)ar

rang

e,in

am

anne

rco

nsis

tent

with

the

requ

irem

ents

ofth

isL

icen

se,

toex

tend

the

pate

ntlic

ense

todo

wns

trea

mre

cipi

ents

.“K

now

-in

gly

rely

ing”

mea

nsyo

uha

veac

tual

know

ledg

eth

at,

but

for

the

pate

ntlic

ense

,you

rco

nvey

-in

gth

eco

vere

dw

ork

ina

coun

-tr

y,or

your

reci

pien

t’sus

eof

the

cove

red

wor

kin

aco

untr

y,w

ould

infr

inge

one

orm

ore

iden

-tifi

able

pate

nts

inth

atco

untr

yth

atyo

uha

vere

ason

tobe

lieve

are

valid

.

If,p

ursu

ant

toor

inco

nnec

tion

with

asi

ngle

tran

sact

ion

orar

-ra

ngem

ent,

you

conv

ey,o

rpro

p-ag

ate

bypr

ocur

ing

conv

eyan

ceof

,aco

vere

dw

ork,

and

gran

tapa

tent

licen

seto

som

eof

the

par-

ties

rece

ivin

gth

eco

vere

dw

ork

auth

oriz

ing

them

tous

e,pr

op-

agat

e,m

odif

yor

conv

eya

spe-

cific

copy

ofth

eco

vere

dw

ork,

then

the

pate

ntlic

ense

you

gran

tis

auto

mat

ical

lyex

tend

edto

all

reci

pien

tsof

the

cove

red

wor

kan

dw

orks

base

don

it.

Apa

tent

licen

seis

“dis

crim

i-na

tory

”if

itdo

esno

tin

clud

ew

ithin

the

scop

eof

itsco

vera

ge,

proh

ibits

the

exer

cise

of,

oris

cond

ition

edon

the

non-

exer

cise

ofon

eor

mor

eof

the

righ

tsth

atar

esp

ecifi

cally

gran

ted

unde

rth

isL

icen

se.

You

may

notc

on-

vey

aco

vere

dw

ork

ifyo

uar

ea

part

yto

anar

rang

emen

tw

itha

thir

dpa

rty

that

isin

the

busi

ness

ofdi

stri

butin

gso

ftw

are,

unde

rw

hich

you

mak

epa

ymen

tto

the

thir

dpa

rty

base

don

the

exte

ntof

your

activ

ityof

conv

eyin

gth

ew

ork,

and

unde

rwhi

chth

eth

ird

part

ygr

ants

,to

any

ofth

epa

r-tie

sw

how

ould

rece

ive

the

cov-

ered

wor

kfr

omyo

u,a

disc

rim

i-na

tory

pate

ntlic

ense

(a)

inco

n-ne

ctio

nw

ithco

pies

ofth

eco

v-er

edw

ork

conv

eyed

byyo

u(o

rco

pies

mad

efr

omth

ose

copi

es),

or(b

)pr

imar

ilyfo

ran

din

con-

nect

ion

with

spec

ific

prod

ucts

orco

mpi

latio

nsth

atco

ntai

nth

eco

vere

dw

ork,

unle

ssyo

uen

-

tere

din

toth

atar

rang

emen

t,or

that

pate

ntlic

ense

was

gran

ted,

prio

rto

28M

arch

2007

.

Not

hing

inth

isL

icen

sesh

all

beco

nstr

ued

asex

clud

ing

orlim

iting

any

impl

ied

licen

seor

othe

rde

fens

esto

infr

inge

men

tth

atm

ayot

herw

ise

beav

aila

ble

toyo

uun

der

appl

icab

lepa

tent

law

.12

.N

oSu

rren

der

ofO

th-

ers’

Free

dom

.

Ifco

nditi

ons

are

impo

sed

onyo

u(w

heth

erby

cour

tor

der,

agre

emen

tor

othe

rwis

e)th

atco

ntra

dict

the

cond

ition

sof

this

Lic

ense

,the

ydo

note

xcus

eyo

ufr

omth

eco

nditi

ons

ofth

isL

i-ce

nse.

Ifyo

uca

nnot

conv

eya

cove

red

wor

kso

asto

sat-

isfy

sim

ulta

neou

sly

your

oblig

a-tio

nsun

dert

his

Lic

ense

and

any

othe

rper

tinen

tobl

igat

ions

,the

nas

aco

nseq

uenc

eyo

um

ayno

tco

nvey

itat

all.

For

exam

ple,

ifyo

uag

ree

tote

rms

that

ob-

ligat

eyo

uto

colle

cta

roya

ltyfo

rfur

ther

conv

eyin

gfr

omth

ose

tow

hom

you

conv

eyth

ePr

o-gr

am,

the

only

way

you

coul

dsa

tisfy

both

thos

ete

rms

and

this

Lic

ense

wou

ldbe

tore

frai

nen

-tir

ely

from

conv

eyin

gth

ePr

o-

Page 368: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

gram

.13

.U

sew

ithth

eG

NU

Aff

ero

Gen

eral

Publ

icL

icen

se.

Not

with

stan

ding

any

othe

rpr

o-vi

sion

ofth

isL

icen

se,y

ouha

vepe

rmis

sion

tolin

kor

com

bine

any

cove

red

wor

kw

itha

wor

klic

ense

dun

der

vers

ion

3of

the

GN

UA

ffer

oG

ener

alPu

blic

Li-

cens

ein

toa

sing

leco

mbi

ned

wor

k,an

dto

conv

eyth

ere

sult-

ing

wor

k.T

hete

rms

ofth

isL

i-ce

nse

will

cont

inue

toap

ply

toth

epa

rtw

hich

isth

eco

vere

dw

ork,

but

the

spec

ial

requ

ire-

men

tsof

the

GN

UA

ffer

oG

en-

eral

Publ

icL

icen

se,

sect

ion

13,

conc

erni

ngin

tera

ctio

nth

roug

ha

netw

ork

will

appl

yto

the

com

-bi

natio

nas

such

.14

.R

evis

edV

ersi

ons

ofth

isL

icen

se.

The

Free

Soft

war

eFo

unda

tion

may

publ

ish

revi

sed

and/

orne

wve

rsio

nsof

the

GN

UG

ener

alPu

blic

Lic

ense

from

time

totim

e.Su

chne

wve

rsio

nsw

illbe

sim

ilari

nsp

irit

toth

epr

esen

tve

rsio

n,bu

tmay

diff

erin

deta

ilto

addr

ess

new

prob

lem

sor

con-

cern

s.

Eac

hve

rsio

nis

give

na

dist

in-

guis

hing

vers

ion

num

ber.

If

the

Prog

ram

spec

ifies

that

ace

r-ta

innu

mbe

red

vers

ion

ofth

eG

NU

Gen

eral

Publ

icL

icen

se“o

ran

yla

ter

vers

ion”

appl

ies

toit,

you

have

the

optio

nof

fol-

low

ing

the

term

san

dco

nditi

ons

eith

erof

that

num

bere

dve

rsio

nor

ofan

yla

terv

ersi

onpu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

da-

tion.

Ifth

ePr

ogra

mdo

esno

tsp

ecif

ya

vers

ion

num

ber

ofth

eG

NU

Gen

eral

Publ

icL

icen

se,

you

may

choo

sean

yve

rsio

nev

erpu

blis

hed

byth

eFr

eeSo

ft-

war

eFo

unda

tion.

Ifth

ePr

ogra

msp

ecifi

esth

ata

prox

yca

nde

cide

whi

chfu

ture

vers

ions

ofth

eG

NU

Gen

eral

Publ

icL

icen

seca

nbe

used

,tha

tpr

oxy’

spu

blic

stat

emen

tof

ac-

cept

ance

ofa

vers

ion

perm

a-ne

ntly

auth

oriz

esyo

uto

choo

seth

atve

rsio

nfo

rthe

Prog

ram

.

Lat

erlic

ense

vers

ions

may

give

you

addi

tiona

lor

diff

eren

tpe

r-m

issi

ons.

How

ever

,no

addi

-tio

nal

oblig

atio

nsar

eim

pose

don

any

auth

oror

copy

righ

tho

lder

asa

resu

ltof

your

choo

s-in

gto

follo

wa

late

rver

sion

.15

.D

iscl

aim

erof

War

rant

y.

TH

ER

EIS

NO

WA

RR

AN

TY

FOR

TH

EPR

OG

RA

M,

TOT

HE

EX

TE

NT

PER

MIT

TE

DB

YA

PPL

ICA

BL

EL

AW

.E

X-

CE

PTW

HE

NO

TH

ER

WIS

EST

AT

ED

INW

RIT

ING

TH

EC

OPY

RIG

HT

HO

LD

ER

SA

ND

/OR

OT

HE

RPA

RT

IES

PRO

VID

ET

HE

PRO

GR

AM

“AS

IS”

WIT

HO

UT

WA

R-

RA

NT

YO

FA

NY

KIN

D,

EIT

HE

RE

XPR

ESS

ED

OR

IMPL

IED

,IN

CL

UD

ING

,B

UT

NO

TL

IMIT

ED

TO,

TH

EIM

PLIE

DW

AR

RA

NT

IES

OF

ME

RC

HA

NTA

BIL

ITY

AN

DFI

TN

ESS

FOR

APA

R-

TIC

UL

AR

PUR

POSE

.T

HE

EN

TIR

ER

ISK

AS

TOT

HE

QU

AL

ITY

AN

DPE

RFO

R-

MA

NC

EO

FT

HE

PRO

GR

AM

ISW

ITH

YO

U.S

HO

UL

DT

HE

PRO

GR

AM

PRO

VE

DE

FEC

-T

IVE

,Y

OU

ASS

UM

ET

HE

CO

STO

FA

LL

NE

CE

SSA

RYSE

RVIC

ING

,R

EPA

IRO

RC

OR

RE

CT

ION

.16.

Lim

itatio

nof

Lia

bilit

y.

INN

OE

VE

NT

UN

LE

SSR

EQ

UIR

ED

BY

APP

LIC

A-

BL

EL

AW

OR

AG

RE

ED

TOIN

WR

ITIN

GW

ILL

AN

YC

OPY

RIG

HT

HO

LD

ER

,

OR

AN

YO

TH

ER

PAR

TY

WH

OM

OD

IFIE

SA

ND

/OR

CO

NV

EY

ST

HE

PRO

GR

AM

AS

PER

MIT

TE

DA

BO

VE

,B

EL

IAB

LE

TOY

OU

FOR

DA

MA

GE

S,IN

CL

UD

ING

AN

YG

EN

ER

AL

,SP

EC

IAL

,IN

CID

EN

TAL

OR

CO

N-

SEQ

UE

NT

IAL

DA

MA

GE

SA

RIS

ING

OU

TO

FT

HE

USE

OR

INA

BIL

ITY

TOU

SET

HE

PRO

GR

AM

(IN

CL

UD

ING

BU

TN

OT

LIM

ITE

DTO

LO

SSO

FD

ATA

OR

DA

TAB

EIN

GR

EN

DE

RE

DIN

AC

CU

RA

TE

OR

LO

SSE

SSU

STA

INE

DB

YY

OU

OR

TH

IRD

PAR

TIE

SO

RA

FAIL

UR

EO

FT

HE

PRO

-G

RA

MTO

OPE

RA

TE

WIT

HA

NY

OT

HE

RPR

OG

RA

MS)

,E

VE

NIF

SUC

HH

OL

DE

RO

RO

TH

ER

PAR

TY

HA

SB

EE

NA

DV

ISE

DO

FT

HE

POSS

IBIL

-IT

YO

FSU

CH

DA

MA

GE

S.17

.In

terp

reta

tion

ofSe

ctio

ns15

and

16.

Ifth

edi

scla

imer

ofw

arra

nty

and

limita

tion

oflia

bilit

ypr

o-vi

ded

abov

eca

nnot

begi

ven

loca

lle

gal

effe

ctac

cord

ing

toth

eir

term

s,re

view

ing

cour

tssh

all

appl

ylo

cal

law

that

mos

tcl

osel

yap

prox

imat

esan

abso

-

Page 369: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

lute

wai

ver

ofal

lci

vil

liabi

lity

inco

nnec

tion

with

the

Prog

ram

,un

less

aw

arra

nty

oras

sum

ptio

nof

liabi

lity

acco

mpa

nies

aco

pyof

the

Prog

ram

inre

turn

for

afe

e.

EN

DO

FT

ER

MS

AN

DC

ON

-D

ITIO

NS

How

toA

pply

The

seTe

rms

toY

ourN

ewPr

ogra

ms

Ifyo

ude

velo

pa

new

prog

ram

,an

dyo

uw

ant

itto

beof

the

grea

test

poss

ible

use

toth

epu

b-lic

,the

best

way

toac

hiev

eth

isis

tom

ake

itfr

eeso

ftw

are

whi

chev

eryo

neca

nre

dist

ribu

tean

dch

ange

unde

rthe

sete

rms.

Todo

so,

atta

chth

efo

llow

ing

notic

esto

the

prog

ram

.It

issa

fest

toat

tach

them

toth

est

art

ofea

chso

urce

file

tom

oste

ffec

-tiv

ely

stat

eth

eex

clus

ion

ofw

ar-

rant

y;an

dea

chfil

esh

ould

have

atle

astt

he“c

opyr

ight

”lin

ean

da

poin

tert

ow

here

the

full

notic

eis

foun

d.

<one

line

togi

veth

epr

ogra

m’s

nam

ean

da

brie

fid

eaof

wha

tit

does

.>C

opyr

ight

(C)

<yea

r><n

ame

ofau

thor

>

Thi

spr

ogra

mis

free

soft

war

e:yo

uca

nre

dist

ribu

teit

and/

orm

odif

yit

unde

rthe

term

sof

the

GN

UG

ener

alPu

blic

Lic

ense

aspu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

datio

n,ei

ther

vers

ion

3of

the

Lic

ense

,or

(at

your

optio

n)an

yla

terv

ersi

on.

Thi

spr

ogra

mis

dist

ribu

ted

inth

eho

peth

atit

will

beus

eful

,bu

tW

ITH

OU

TA

NY

WA

RR

AN

TY

;w

ithou

tev

enth

eim

plie

dw

arra

nty

ofM

ER

-C

HA

NTA

BIL

ITY

orFI

TN

ESS

FOR

APA

RT

ICU

LA

RPU

R-

POSE

.Se

eth

eG

NU

Gen

eral

Publ

icL

icen

sefo

rmor

ede

tails

.

You

shou

ldha

vere

ceiv

eda

copy

ofth

eG

NU

Gen

eral

Publ

icL

icen

seal

ong

with

this

prog

ram

.If

not,

see

<http

://w

ww

.gnu

.org

/lice

nses

/>.

Als

oad

din

form

atio

non

how

toco

ntac

tyo

uby

elec

tron

ican

dpa

perm

ail.

Ifth

epr

ogra

mdo

este

rmin

alin

-te

ract

ion,

mak

eit

outp

uta

shor

tno

tice

like

this

whe

nit

star

tsin

anin

tera

ctiv

em

ode:

<pro

gram

>C

opyr

ight

(C)

<yea

r><n

ame

ofau

thor

>T

his

prog

ram

com

esw

ithA

BSO

-L

UT

ELY

NO

WA

RR

AN

TY

;fo

rde

tails

type

‘sho

ww

’.T

his

isfr

eeso

ftw

are,

and

you

are

wel

com

eto

redi

stri

bute

itun

der

cert

ain

cond

ition

s;ty

pe‘s

how

c’fo

rdet

ails

.

The

hypo

thet

ical

com

man

ds‘s

how

w’

and

‘sho

wc’

shou

ldsh

owth

eap

prop

riat

epa

rts

ofth

eG

ener

alPu

blic

Lic

ense

.O

fco

urse

,yo

urpr

ogra

m’s

com

-m

ands

mig

htbe

diff

eren

t;fo

ra

GU

Iin

terf

ace,

you

wou

ldus

ean

“abo

utbo

x”.

You

shou

ldal

soge

tyo

urem

ploy

er(i

fyo

uw

ork

asa

prog

ram

mer

)or

scho

ol,

ifan

y,to

sign

a“c

opyr

ight

dis-

clai

mer

”fo

rth

epr

ogra

m,

ifne

cess

ary.

For

mor

ein

form

a-tio

non

this

,an

dho

wto

appl

yan

dfo

llow

the

GN

UG

PL,

see

<http

://w

ww

.gnu

.org

/lice

nses

/>.

The

GN

UG

ener

alPu

blic

Lic

ense

does

not

perm

itin

-co

rpor

atin

gyo

urpr

ogra

min

topr

opri

etar

ypr

ogra

ms.

Ifyo

urpr

ogra

mis

asu

brou

tine

libra

ry,

you

may

cons

ider

itm

ore

usef

ulto

perm

itlin

king

prop

riet

ary

appl

icat

ions

with

the

libra

ry.

Ifth

isis

wha

tyo

uw

ant

todo

,us

eth

eG

NU

Les

ser

Gen

eral

Publ

icL

icen

sein

stea

dof

this

Lic

ense

.B

utfir

st,

plea

sere

ad<h

ttp://

ww

w.g

nu.o

rg/p

hilo

soph

y/w

hy-

not-

lgpl

.htm

l>.

36.2

GN

UFr

eeD

ocum

enta

tion

Lic

ense

Page 370: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

Ver

sion

1.3,

3N

ovem

ber2

008

Cop

yrig

ht©

2000

,20

01,

2002

,20

07,2

008

Free

Soft

war

eFo

un-

datio

n,In

c.<h

ttp://

fsf.o

rg/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

not

allo

wed

.0.

PRE

AM

BL

E

The

purp

ose

ofth

isL

icen

seis

tom

ake

am

anua

l,te

xtbo

ok,o

rot

her

func

tiona

land

usef

uldo

c-um

ent

"fre

e"in

the

sens

eof

free

dom

:to

assu

reev

eryo

neth

eef

fect

ive

free

dom

toco

pyan

dre

dist

ribu

teit,

with

orw

ith-

out

mod

ifyi

ngit,

eith

erco

m-

mer

cial

lyor

nonc

omm

erci

ally

.Se

cond

arily

,th

isL

icen

sepr

e-se

rves

for

the

auth

oran

dpu

b-lis

her

aw

ayto

get

cred

itfo

rth

eirw

ork,

whi

leno

tbei

ngco

n-si

dere

dre

spon

sibl

efo

rm

odifi

-ca

tions

mad

eby

othe

rs.

Thi

sL

icen

seis

aki

ndof

"cop

y-le

ft",

whi

chm

eans

that

deriv

a-tiv

ew

orks

ofth

edo

cum

entm

ust

them

selv

esbe

free

inth

esa

me

sens

e.It

com

plem

ents

the

GN

UG

ener

alPu

blic

Lic

ense

,w

hich

isa

copy

left

licen

sede

sign

edfo

rfre

eso

ftw

are.

We

have

desi

gned

this

Lic

ense

inor

der

tous

eit

for

man

uals

for

free

soft

war

e,be

caus

efr

eeso

ftw

are

need

sfr

eedo

cum

en-

tatio

n:a

free

prog

ram

shou

ldco

me

with

man

uals

prov

idin

gth

esa

me

free

dom

sth

atth

eso

ft-

war

edo

es.

But

this

Lic

ense

isno

tlim

ited

toso

ftw

are

man

u-al

s;it

can

beus

edfo

ran

yte

x-tu

alw

ork,

rega

rdle

ssof

subj

ect

mat

tero

rwhe

ther

itis

publ

ishe

das

apr

inte

dbo

ok.

We

reco

m-

men

dth

isL

icen

sepr

inci

pally

for

wor

ksw

hose

purp

ose

isin

-st

ruct

ion

orre

fere

nce.

1.A

P-PL

ICA

BIL

ITY

AN

DD

EFI

NI-

TIO

NS

Thi

sL

icen

seap

plie

sto

any

man

ual

orot

her

wor

k,in

any

med

ium

,th

atco

ntai

nsa

notic

epl

aced

byth

eco

pyri

ght

hold

ersa

ying

itca

nbe

dist

ribu

ted

un-

der

the

term

sof

this

Lic

ense

.Su

cha

notic

egr

ants

aw

orld

-w

ide,

roya

lty-f

ree

licen

se,

un-

limite

din

dura

tion,

tous

eth

atw

ork

unde

rthe

cond

ition

ssta

ted

here

in.T

he"D

ocum

ent"

,bel

ow,

refe

rsto

any

such

man

ual

or

wor

k.A

nym

embe

rof

the

pub-

licis

alic

ense

e,an

dis

addr

esse

das

"you

".Y

ouac

cept

the

licen

seif

you

copy

,mod

ify

ordi

stri

bute

the

wor

kin

aw

ayre

quir

ing

per-

mis

sion

unde

rcop

yrig

htla

w.

A"M

odifi

edV

ersi

on"

ofth

eD

ocum

entm

eans

any

wor

kco

n-ta

inin

gth

eD

ocum

ent

ora

por-

tion

ofit,

eith

erco

pied

ver-

batim

,or

with

mod

ifica

tions

and/

ortr

ansl

ated

into

anot

her

lang

uage

.

A"S

econ

dary

Sect

ion"

isa

nam

edap

pend

ixor

afr

ont-

mat

ter

sect

ion

ofth

eD

ocum

ent

that

deal

sex

clus

ivel

yw

ithth

ere

latio

nshi

pof

the

publ

ishe

rsor

auth

ors

ofth

eD

ocum

ent

toth

eD

ocum

ent’s

over

all

subj

ect

(or

tore

late

dm

atte

rs)

and

con-

tain

sno

thin

gth

atco

uld

fall

di-

rect

lyw

ithin

that

over

alls

ubje

ct.

(Thu

s,if

the

Doc

umen

tis

inpa

rta

text

book

ofm

athe

mat

ics,

aSe

cond

ary

Sect

ion

may

note

x-pl

ain

any

mat

hem

atic

s.)

The

rela

tions

hip

coul

dbe

am

atte

rof

hist

oric

alco

nnec

tion

with

the

subj

ect

orw

ithre

late

dm

atte

rs,

orof

lega

l,co

mm

erci

al,

philo

-

soph

ical

,eth

ical

orpo

litic

alpo

-si

tion

rega

rdin

gth

em.

The

"Inv

aria

ntSe

ctio

ns"

are

cer-

tain

Seco

ndar

ySe

ctio

nsw

hose

title

sar

ede

sign

ated

,as

bein

gth

ose

ofIn

vari

ant

Sect

ions

,in

the

notic

eth

atsa

ysth

atth

eD

oc-

umen

tis

rele

ased

unde

rth

isL

i-ce

nse.

Ifa

sect

ion

does

not

fitth

eab

ove

defin

ition

ofSe

c-on

dary

then

itis

nota

llow

edto

bede

sign

ated

asIn

vari

ant.

The

Doc

umen

tmay

cont

ain

zero

In-

vari

ant

Sect

ions

.If

the

Doc

u-m

ent

does

not

iden

tify

any

In-

vari

ant

Sect

ions

then

ther

ear

eno

ne.

The

"Cov

erTe

xts"

are

cert

ain

shor

tpa

ssag

esof

text

that

are

liste

d,as

Fron

t-C

over

Text

sor

Bac

k-C

over

Text

s,in

the

no-

tice

that

says

that

the

Doc

umen

tis

rele

ased

unde

rth

isL

icen

se.

AFr

ont-

Cov

erTe

xtm

aybe

atm

ost5

wor

ds,a

nda

Bac

k-C

over

Text

may

beat

mos

t25

wor

ds.

A"T

rans

pare

nt"

copy

ofth

eD

ocum

ent

mea

nsa

mac

hine

-re

adab

leco

py,

repr

esen

ted

ina

form

atw

hose

spec

ifica

tion

isav

aila

ble

toth

ege

nera

lpu

b-

Page 371: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

lic,

that

issu

itabl

efo

rre

vis-

ing

the

docu

men

tst

raig

htfo

r-w

ardl

yw

ithge

neri

cte

xted

i-to

rsor

(for

imag

esco

mpo

sed

ofpi

xels

)ge

neri

cpa

int

pro-

gram

sor

(for

draw

ings

)so

me

wid

ely

avai

labl

edr

awin

ged

itor,

and

that

issu

itabl

efo

rin

put

tote

xtfo

rmat

ters

orfo

rau

tom

atic

tran

slat

ion

toa

vari

ety

offo

r-m

ats

suita

ble

for

inpu

tto

text

form

atte

rs.

Aco

pym

ade

inan

othe

rwis

eTr

ansp

aren

tfil

efo

r-m

atw

hose

mar

kup,

orab

senc

eof

mar

kup,

has

been

arra

nged

toth

war

tord

isco

urag

esu

bseq

uent

mod

ifica

tion

byre

ader

sis

not

Tran

spar

ent.

An

imag

efo

rmat

isno

tTr

ansp

aren

tif

used

for

any

subs

tant

ial

amou

ntof

text

.A

copy

that

isno

t"Tr

ansp

aren

t"is

calle

d"O

paqu

e".

Exa

mpl

esof

suita

ble

form

ats

for

Tran

spar

ent

copi

esin

clud

epl

ain

ASC

IIw

ithou

tm

arku

p,Te

xinf

oin

putf

orm

at,L

aTeX

in-

put

form

at,

SGM

Lor

XM

Lus

-in

ga

publ

icly

avai

labl

eD

TD

,an

dst

anda

rd-c

onfo

rmin

gsi

m-

ple

HT

ML

,Po

stSc

ript

orPD

Fde

sign

edfo

rhu

man

mod

ifica

-tio

n.E

xam

ples

oftr

ansp

ar-

enti

mag

efo

rmat

sin

clud

ePN

G,

XC

Fan

dJP

G.O

paqu

efo

rmat

sin

clud

epr

opri

etar

yfo

rmat

sth

atca

nbe

read

and

edite

don

lyby

prop

riet

ary

wor

dpr

oces

sors

,SG

ML

orX

ML

for

whi

chth

eD

TD

and/

orpr

oces

sing

tool

sar

eno

tge

nera

llyav

aila

ble,

and

the

mac

hine

-gen

erat

edH

TM

L,

Post

Scri

ptor

PDF

prod

uced

byso

me

wor

dpr

oces

sors

for

out-

putp

urpo

ses

only

.

The

"Titl

ePa

ge"

mea

ns,

for

apr

inte

dbo

ok,

the

title

page

it-se

lf,

plus

such

follo

win

gpa

ges

asar

ene

eded

toho

ld,

legi

-bl

y,th

em

ater

ialt

his

Lic

ense

re-

quir

esto

appe

arin

the

title

page

.Fo

rw

orks

info

rmat

sw

hich

dono

tha

vean

ytit

lepa

geas

such

,"T

itle

Page

"m

eans

the

text

near

the

mos

tpr

omin

ent

appe

aran

ceof

the

wor

k’st

itle,

prec

edin

gth

ebe

ginn

ing

ofth

ebo

dyof

the

text

.

The

"pub

lishe

r"m

eans

any

per-

son

oren

tity

that

dist

ribu

tes

copi

esof

the

Doc

umen

tto

the

publ

ic.

Ase

ctio

n"E

ntitl

edX

YZ

"m

eans

ana

med

subu

nit

ofth

eD

ocum

ent

who

setit

leei

ther

ispr

ecis

ely

XY

Zor

cont

ains

XY

Zin

pare

nthe

ses

follo

win

gte

xtth

attr

ansl

ates

XY

Zin

anot

her

lang

uage

.(H

ere

XY

Zst

ands

for

asp

ecifi

cse

ctio

nna

me

men

tione

dbe

low

,su

chas

"Ack

now

ledg

emen

ts",

"Ded

-ic

atio

ns",

"End

orse

men

ts",

or"H

isto

ry".

)To

"Pre

serv

eth

eTi

tle"

ofsu

cha

sect

ion

whe

nyo

um

odif

yth

eD

ocum

ent

mea

nsth

atit

rem

ains

ase

ctio

n"E

ntitl

edX

YZ

"ac

cord

ing

toth

isde

finiti

on.

The

Doc

umen

tm

ayin

clud

eW

arra

nty

Dis

clai

mer

sne

xtto

the

notic

ew

hich

stat

esth

atth

isL

icen

seap

plie

sto

the

Doc

u-m

ent.

The

seW

arra

nty

Dis

-cl

aim

ers

are

cons

ider

edto

bein

-cl

uded

byre

fere

nce

inth

isL

i-ce

nse,

but

only

asre

gard

sdi

s-cl

aim

ing

war

rant

ies:

any

othe

rim

plic

atio

nth

atth

ese

War

rant

yD

iscl

aim

ers

may

have

isvo

idan

dha

sno

effe

cton

the

mea

n-in

gof

this

Lic

ense

.2.

VE

RB

A-

TIM

CO

PYIN

G

You

may

copy

and

dist

ribu

teth

eD

ocum

ent

inan

ym

ediu

m,

ei-

ther

com

mer

cial

lyor

nonc

om-

mer

cial

ly,p

rovi

ded

that

this

Li-

cens

e,th

eco

pyri

ght

notic

es,

and

the

licen

seno

tice

sayi

ngth

isL

icen

seap

plie

sto

the

Doc

-um

ent

are

repr

oduc

edin

all

copi

es,

and

that

you

add

noot

her

cond

ition

sw

hats

oeve

rto

thos

eof

this

Lic

ense

.Y

oum

ayno

tus

ete

chni

cal

mea

sure

sto

obst

ruct

orco

ntro

lth

ere

adin

gor

furt

her

copy

ing

ofth

eco

pies

you

mak

eor

dist

ribu

te.

How

-ev

er,

you

may

acce

ptco

mpe

n-sa

tion

inex

chan

gefo

rco

pies

.If

you

dist

ribu

tea

larg

een

ough

num

bero

fcop

ies

you

mus

tals

ofo

llow

the

cond

ition

sin

sect

ion

3. You

may

also

lend

copi

es,

un-

der

the

sam

eco

nditi

ons

stat

edab

ove,

and

you

may

publ

icly

disp

lay

copi

es.

3.C

OPY

ING

INQ

UA

NT

ITY

Ifyo

upu

blis

hpr

inte

dco

pies

(or

copi

esin

med

iath

atco

mm

only

have

prin

ted

cove

rs)o

fthe

Doc

-um

ent,

num

beri

ngm

ore

than

100,

and

the

Doc

umen

t’slic

ense

notic

ere

quir

esC

over

Text

s,yo

um

ust

encl

ose

the

copi

esin

cov-

ers

that

carr

y,cl

earl

yan

dle

gi-

bly,

allt

hese

Cov

erTe

xts:

Fron

t-C

over

Text

son

the

fron

tco

ver,

Page 372: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

and

Bac

k-C

over

Text

son

the

back

cove

r.B

oth

cove

rsm

ust

also

clea

rly

and

legi

bly

iden

tify

you

asth

epu

blis

her

ofth

ese

copi

es.

The

fron

tco

ver

mus

tpr

esen

tth

efu

lltit

lew

ithal

lw

ords

ofth

etit

leeq

ually

prom

i-ne

ntan

dvi

sibl

e.Y

oum

ayad

dot

her

mat

eria

lon

the

cove

rsin

addi

tion.

Cop

ying

with

chan

ges

limite

dto

the

cove

rs,

aslo

ngas

they

pres

erve

the

title

ofth

eD

ocum

enta

ndsa

tisfy

thes

eco

n-di

tions

,can

betr

eate

das

verb

a-tim

copy

ing

inot

herr

espe

cts.

Ifth

ere

quir

edte

xts

for

eith

erco

ver

are

too

volu

min

ous

tofit

legi

bly,

you

shou

ldpu

tthe

first

ones

liste

d(a

sm

any

asfit

rea-

sona

bly)

onth

eac

tual

cove

r,an

dco

ntin

ueth

ere

ston

toad

ja-

cent

page

s.

Ifyo

upu

blis

hor

dist

ribu

teO

paqu

eco

pies

ofth

eD

oc-

umen

tnu

mbe

ring

mor

eth

an10

0,yo

um

ust

eith

erin

clud

ea

mac

hine

-rea

dabl

eTr

ansp

aren

tco

pyal

ong

with

each

Opa

que

copy

,or

stat

ein

orw

ithea

chO

paqu

eco

pya

com

pute

r-ne

twor

klo

catio

nfr

omw

hich

the

gene

ral

netw

ork-

usin

gpu

b-

licha

sacc

esst

odo

wnl

oad

usin

gpu

blic

-sta

ndar

dne

twor

kpr

oto-

cols

aco

mpl

ete

Tran

spar

ent

copy

ofth

eD

ocum

ent,

free

ofad

ded

mat

eria

l.If

you

use

the

latte

rop

tion,

you

mus

tta

kere

ason

ably

prud

ent

step

s,w

hen

you

begi

ndi

stri

butio

nof

Opa

que

copi

esin

quan

tity,

toen

-su

reth

atth

isTr

ansp

aren

tco

pyw

illre

mai

nth

usac

cess

ible

atth

est

ated

loca

tion

until

atle

ast

one

year

afte

rth

ela

sttim

eyo

udi

stri

bute

anO

paqu

eco

py(d

i-re

ctly

orth

roug

hyo

urag

ents

orre

taile

rs)

ofth

ated

ition

toth

epu

blic

.

Itis

requ

este

d,bu

tnot

requ

ired

,th

atyo

uco

ntac

tth

eau

thor

sof

the

Doc

umen

twel

lbef

ore

redi

s-tr

ibut

ing

any

larg

enu

mbe

rof

copi

es,t

ogi

veth

ema

chan

ceto

prov

ide

you

with

anup

date

dve

r-si

onof

the

Doc

umen

t.4.

MO

D-

IFIC

AT

ION

S

You

may

copy

and

dist

ribu

tea

Mod

ified

Ver

sion

ofth

eD

oc-

umen

tun

der

the

cond

ition

sof

sect

ions

2an

d3

abov

e,pr

ovid

edth

atyo

ure

leas

eth

eM

odifi

edV

ersi

onun

der

prec

isel

yth

isL

i-ce

nse,

with

the

Mod

ified

Ver

-

sion

fillin

gth

ero

leof

the

Doc

u-m

ent,

thus

licen

sing

dist

ribu

tion

and

mod

ifica

tion

ofth

eM

od-

ified

Ver

sion

tow

hoev

erpo

s-se

sses

aco

pyof

it.In

addi

tion,

you

mus

tdo

thes

eth

ings

inth

eM

odifi

edV

ersi

on:

*A

.Use

inth

eTi

tlePa

ge(a

ndon

the

cove

rs,i

fan

y)a

title

dis-

tinct

from

that

ofth

eD

ocum

ent,

and

from

thos

eof

prev

ious

ver-

sion

s(w

hich

shou

ld,

ifth

ere

wer

ean

y,be

liste

din

the

His

-to

ryse

ctio

nof

the

Doc

umen

t).

You

may

use

the

sam

etit

leas

apr

evio

usve

rsio

nif

the

orig

inal

publ

ishe

rof

that

vers

ion

give

spe

rmis

sion

.*

B.

Lis

ton

the

Title

Page

,as

auth

ors,

one

orm

ore

pers

ons

oren

titie

sre

spon

-si

ble

for

auth

orsh

ipof

the

mod

-ifi

catio

nsin

the

Mod

ified

Ver

-si

on,

toge

ther

with

atle

ast

five

ofth

epr

inci

pal

auth

ors

ofth

eD

ocum

ent

(all

ofits

prin

cipa

lau

thor

s,if

itha

sfew

erth

anfiv

e),

unle

ssth

eyre

leas

eyo

ufr

omth

isre

quir

emen

t.*

C.S

tate

onth

eTi

tlepa

geth

ena

me

ofth

epu

blis

her

ofth

eM

odifi

edV

er-

sion

,as

the

publ

ishe

r.*

D.P

re-

serv

eal

lth

eco

pyri

ght

notic

esof

the

Doc

umen

t.*

E.

Add

anap

prop

riat

eco

pyri

ght

notic

efo

ryo

urm

odifi

catio

nsad

jace

ntto

the

othe

rco

pyri

ght

notic

es.

*F.

Incl

ude,

imm

edia

tely

afte

rth

eco

pyri

ght

notic

es,

alic

ense

notic

egi

ving

the

publ

icpe

rmis

-si

onto

use

the

Mod

ified

Ver

sion

unde

rth

ete

rms

ofth

isL

icen

se,

inth

efo

rmsh

own

inth

eA

dden

-du

mbe

low

.*G

.Pre

serv

ein

that

licen

seno

tice

the

full

lists

ofIn

vari

ant

Sect

ions

and

requ

ired

Cov

erTe

xts

give

nin

the

Doc

u-m

ent’s

licen

seno

tice.

*H

.In

-cl

ude

anun

alte

red

copy

ofth

isL

icen

se.

*I.

Pres

erve

the

sec-

tion

Ent

itled

"His

tory

",Pr

eser

veits

Title

,an

dad

dto

itan

item

stat

ing

atle

ast

the

title

,ye

ar,

new

auth

ors,

and

publ

ishe

rof

the

Mod

ified

Ver

sion

asgi

ven

onth

eTi

tlePa

ge.

Ifth

ere

isno

sect

ion

Ent

itled

"His

tory

"in

the

Doc

umen

t,cr

eate

one

stat

-in

gth

etit

le,

year

,au

thor

s,an

dpu

blis

her

ofth

eD

ocum

ent

asgi

ven

onits

Title

Page

,the

nad

dan

item

desc

ribi

ngth

eM

odifi

edV

ersi

onas

stat

edin

the

prev

i-ou

sse

nten

ce.

*J.

Pres

erve

the

netw

ork

loca

tion,

ifan

y,gi

ven

inth

eD

ocum

ent

for

publ

icac

-ce

ssto

aTr

ansp

aren

tco

pyof

the

Doc

umen

t,an

dlik

ewis

eth

e

Page 373: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

netw

ork

loca

tions

give

nin

the

Doc

umen

tfor

prev

ious

vers

ions

itw

asba

sed

on.

The

sem

aybe

plac

edin

the

"His

tory

"se

c-tio

n.Y

oum

ayom

ita

netw

ork

loca

tion

for

aw

ork

that

was

publ

ishe

dat

leas

tfou

rye

ars

be-

fore

the

Doc

umen

tits

elf,

orif

the

orig

inal

publ

ishe

roft

heve

r-si

onit

refe

rsto

give

sper

mis

sion

.*

K.

For

any

sect

ion

Ent

itled

"Ack

now

ledg

emen

ts"

or"D

edi-

catio

ns",

Pres

erve

the

Title

ofth

ese

ctio

n,an

dpr

eser

vein

the

sect

ion

all

the

subs

tanc

ean

dto

neof

each

ofth

eco

ntri

buto

rac

know

ledg

emen

tsan

d/or

dedi

-ca

tions

give

nth

erei

n.*

L.P

re-

serv

eal

lth

eIn

vari

ant

Sect

ions

ofth

eD

ocum

ent,

unal

tere

din

thei

rtex

tand

inth

eirt

itles

.Sec

-tio

nnu

mbe

rsor

the

equi

vale

ntar

eno

tco

nsid

ered

part

ofth

ese

ctio

ntit

les.

*M

.D

elet

ean

yse

ctio

nE

ntitl

ed"E

ndor

se-

men

ts".

Such

ase

ctio

nm

ayno

tbe

incl

uded

inth

eM

odifi

edV

er-

sion

.*

N.D

ono

tret

itle

any

ex-

istin

gse

ctio

nto

beE

ntitl

ed"E

n-do

rsem

ents

"or

toco

nflic

tin

ti-tle

with

any

Inva

rian

tSec

tion.

*O

.Pr

eser

vean

yW

arra

nty

Dis

-cl

aim

ers.

Ifth

eM

odifi

edV

ersi

onin

clud

esne

wfr

ont-

mat

ter

sect

ions

orap

-pe

ndic

esth

atqu

alif

yas

Sec-

onda

rySe

ctio

nsan

dco

ntai

nno

mat

eria

lco

pied

from

the

Doc

u-m

ent,

you

may

atyo

urop

tion

desi

gnat

eso

me

oral

lof

thes

ese

ctio

nsas

inva

rian

t.To

doth

is,

add

thei

rtit

les

toth

elis

tof

In-

vari

antS

ectio

nsin

the

Mod

ified

Ver

sion

’slic

ense

notic

e.T

hese

title

sm

ust

bedi

stin

ctfr

oman

yot

hers

ectio

ntit

les.

You

may

add

ase

ctio

nE

nti-

tled

"End

orse

men

ts",

prov

ided

itco

ntai

nsno

thin

gbu

ten

dors

e-m

ents

ofyo

urM

odifi

edV

ersi

onby

vari

ous

part

ies—

for

exam

-pl

e,st

atem

ents

ofpe

erre

view

orth

atth

ete

xtha

sbe

enap

prov

edby

anor

gani

zatio

nas

the

auth

or-

itativ

ede

finiti

onof

ast

anda

rd.

You

may

add

apa

ssag

eof

upto

five

wor

dsas

aFr

ont-

Cov

erTe

xt,

and

apa

ssag

eof

upto

25w

ords

asa

Bac

k-C

over

Text

,to

the

end

ofth

elis

tof

Cov

erTe

xtsi

nth

eM

odifi

edV

er-

sion

.Onl

yon

epa

ssag

eof

Fron

t-C

over

Text

and

one

ofB

ack-

Cov

erTe

xtm

aybe

adde

dby

(or

thro

ugh

arra

ngem

ents

mad

e

by)

any

one

entit

y.If

the

Doc

-um

ent

alre

ady

incl

udes

aco

ver

text

for

the

sam

eco

ver,

prev

i-ou

sly

adde

dby

you

orby

ar-

rang

emen

tmad

eby

the

sam

een

-tit

yyo

uar

eac

ting

onbe

half

of,

you

may

not

add

anot

her;

but

you

may

repl

ace

the

old

one,

onex

plic

itpe

rmis

sion

from

the

pre-

viou

spu

blis

her

that

adde

dth

eol

don

e.

The

auth

or(s

)an

dpu

blis

her(

s)of

the

Doc

umen

tdo

notb

yth

isL

icen

segi

vepe

rmis

sion

tous

eth

eir

nam

esfo

rpu

blic

ityfo

ror

toas

sert

orim

ply

endo

rsem

ent

ofan

yM

odifi

edV

ersi

on.

5.C

OM

BIN

ING

DO

CU

ME

NT

S

You

may

com

bine

the

Doc

u-m

ent

with

othe

rdo

cum

ents

re-

leas

edun

der

this

Lic

ense

,un

-de

rth

ete

rms

defin

edin

sect

ion

4ab

ove

for

mod

ified

vers

ions

,pr

ovid

edth

atyo

uin

clud

ein

the

com

bina

tion

all

ofth

eIn

vari

-an

tSe

ctio

nsof

all

ofth

eor

igi-

nald

ocum

ents

,unm

odifi

ed,a

ndlis

tth

emal

las

Inva

rian

tSe

c-tio

nsof

your

com

bine

dw

ork

inits

licen

seno

tice,

and

that

you

pres

erve

all

thei

rW

arra

nty

Dis

-cl

aim

ers.

The

com

bine

dw

ork

need

only

cont

ain

one

copy

ofth

isL

icen

se,

and

mul

tiple

iden

tical

Inva

rian

tSe

ctio

nsm

aybe

repl

aced

with

asi

ngle

copy

.If

ther

ear

em

ul-

tiple

Inva

rian

tSec

tions

with

the

sam

ena

me

but

diff

eren

tco

n-te

nts,

mak

eth

etit

leof

each

such

sect

ion

uniq

ueby

addi

ngat

the

end

ofit,

inpa

rent

hese

s,th

ena

me

ofth

eor

igin

alau

thor

orpu

blis

her

ofth

atse

ctio

nif

know

n,or

else

aun

ique

num

-be

r.M

ake

the

sam

ead

just

men

tto

the

sect

ion

title

sin

the

listo

fIn

vari

antS

ectio

nsin

the

licen

seno

tice

ofth

eco

mbi

ned

wor

k.

Inth

eco

mbi

natio

n,yo

um

ust

com

bine

any

sect

ions

Ent

itled

"His

tory

"in

the

vari

ous

orig

i-na

ldoc

umen

ts,f

orm

ing

one

sec-

tion

Ent

itled

"His

tory

";lik

ewis

eco

mbi

nean

yse

ctio

nsE

ntitl

ed"A

ckno

wle

dgem

ents

",an

dan

yse

ctio

nsE

ntitl

ed"D

edic

atio

ns".

You

mus

tdel

ete

alls

ectio

nsE

n-tit

led

"End

orse

men

ts".

6.C

OL

-L

EC

TIO

NS

OF

DO

CU

ME

NT

S

You

may

mak

ea

colle

ctio

nco

n-si

stin

gof

the

Doc

umen

tan

dot

her

docu

men

tsre

leas

edun

der

this

Lic

ense

,and

repl

ace

the

in-

Page 374: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

divi

dual

copi

esof

this

Lic

ense

inth

eva

riou

sdo

cum

ents

with

asi

ngle

copy

that

isin

clud

edin

the

colle

ctio

n,pr

ovid

edth

atyo

ufo

llow

the

rule

sof

this

Lic

ense

for

verb

atim

copy

ing

ofea

chof

the

docu

men

tsin

all

othe

rre

-sp

ects

.

You

may

extr

act

asi

ngle

doc-

umen

tfr

omsu

cha

colle

ctio

n,an

ddi

stri

bute

itin

divi

dual

lyun

-de

rth

isL

icen

se,

prov

ided

you

inse

rta

copy

ofth

isL

icen

sein

toth

eex

trac

ted

docu

men

t,an

dfo

llow

this

Lic

ense

inal

lot

her

resp

ects

rega

rdin

gve

rba-

timco

pyin

gof

that

docu

men

t.7.

AG

GR

EG

AT

ION

WIT

HIN

DE

-PE

ND

EN

TW

OR

KS

Aco

mpi

latio

nof

the

Doc

umen

tor

itsde

rivat

ives

with

othe

rse

para

tean

din

depe

nden

tdo

c-um

ents

orw

orks

,in

oron

avo

lum

eof

ast

orag

eor

dist

ribu

-tio

nm

ediu

m,

isca

lled

an"a

g-gr

egat

e"if

the

copy

righ

tre

sult-

ing

from

the

com

pila

tion

isno

tus

edto

limit

the

lega

lri

ghts

ofth

eco

mpi

latio

n’s

user

sbe

yond

wha

tth

ein

divi

dual

wor

kspe

r-m

it.W

hen

the

Doc

umen

tis

incl

uded

inan

aggr

egat

e,th

is

Lic

ense

does

not

appl

yto

the

othe

rw

orks

inth

eag

greg

ate

whi

char

eno

tthe

mse

lves

deriv

a-tiv

ew

orks

ofth

eD

ocum

ent.

Ifth

eC

over

Text

requ

irem

ento

fse

ctio

n3

isap

plic

able

toth

ese

copi

esof

the

Doc

umen

t,th

enif

the

Doc

umen

tis

less

than

one

half

ofth

een

tire

aggr

egat

e,th

eD

ocum

ent’s

Cov

erTe

xts

may

bepl

aced

onco

vers

that

brac

ket

the

Doc

umen

twith

inth

eag

gre-

gate

,ort

heel

ectr

onic

equi

vale

ntof

cove

rsif

the

Doc

umen

tis

inel

ectr

onic

form

.O

ther

wis

eth

eym

ust

appe

aron

prin

ted

cove

rsth

atbr

acke

tthe

who

leag

greg

ate.

8.T

RA

NSL

AT

ION

Tran

slat

ion

isco

nsid

ered

aki

ndof

mod

ifica

tion,

soyo

um

aydi

s-tr

ibut

etr

ansl

atio

nsof

the

Doc

u-m

entu

nder

the

term

sof

sect

ion

4.R

epla

cing

Inva

rian

tSec

tions

with

tran

slat

ions

requ

ires

spe-

cial

perm

issi

onfr

omth

eir

copy

-ri

ght

hold

ers,

but

you

may

in-

clud

etr

ansl

atio

nsof

som

eor

all

Inva

rian

tSec

tions

inad

ditio

nto

the

orig

inal

vers

ions

ofth

ese

In-

vari

ant

Sect

ions

.Y

oum

ayin

-cl

ude

atr

ansl

atio

nof

this

Li-

cens

e,an

dal

lthe

licen

seno

tices

inth

eD

ocum

ent,

and

any

War

-ra

nty

Dis

clai

mer

s,pr

ovid

edth

atyo

ual

soin

clud

eth

eor

igin

alE

n-gl

ish

vers

ion

ofth

isL

icen

sean

dth

eor

igin

alve

rsio

nsof

thos

eno

-tic

esan

ddi

scla

imer

s.In

case

ofa

disa

gree

men

tbe

twee

nth

etr

ansl

atio

nan

dth

eor

igin

alve

r-si

onof

this

Lic

ense

ora

notic

eor

disc

laim

er,

the

orig

inal

ver-

sion

will

prev

ail.

Ifa

sect

ion

inth

eD

ocum

ent

isE

ntitl

ed"A

ckno

wle

dgem

ents

","D

edic

atio

ns",

or"H

isto

ry",

the

requ

irem

ent

(sec

tion

4)to

Pre-

serv

eits

Title

(sec

tion

1)w

illty

pica

llyre

quir

ech

angi

ngth

eac

tual

title

.9.T

ER

MIN

AT

ION

You

may

notc

opy,

mod

ify,

sub-

licen

se,

ordi

stri

bute

the

Doc

-um

ent

exce

ptas

expr

essl

ypr

o-vi

ded

unde

rth

isL

icen

se.

Any

atte

mpt

othe

rwis

eto

copy

,mod

-if

y,su

blic

ense

,ord

istr

ibut

eit

isvo

id,a

ndw

illau

tom

atic

ally

ter-

min

ate

your

righ

tsun

dert

his

Li-

cens

e.

How

ever

,if

you

ceas

eal

lvio

la-

tion

ofth

isL

icen

se,

then

your

licen

sefr

oma

part

icul

arco

py-

righ

thol

deri

sre

inst

ated

(a)p

ro-

visi

onal

ly,

unle

ssan

dun

tilth

eco

pyri

ght

hold

erex

plic

itly

and

final

lyte

rmin

ates

your

licen

se,

and

(b)p

erm

anen

tly,i

fthe

copy

-ri

ght

hold

erfa

ilsto

notif

yyo

uof

the

viol

atio

nby

som

ere

ason

-ab

lem

eans

prio

rto

60da

ysaf

ter

the

cess

atio

n.

Mor

eove

r,yo

urlic

ense

from

apa

rtic

ular

copy

righ

thol

deri

sre

-in

stat

edpe

rman

ently

ifth

eco

py-

righ

tho

lder

notifi

esyo

uof

the

viol

atio

nby

som

ere

ason

able

mea

ns,t

his

isth

efir

sttim

eyo

uha

vere

ceiv

edno

tice

ofvi

olat

ion

ofth

isL

icen

se(f

oran

yw

ork)

from

that

copy

righ

tho

lder

,and

you

cure

the

viol

atio

npr

ior

to30

days

afte

ryou

rrec

eipt

ofth

eno

tice.

Term

inat

ion

ofyo

urri

ghts

unde

rth

isse

ctio

ndo

esno

tte

rmin

ate

the

licen

ses

ofpa

rtie

sw

hoha

vere

ceiv

edco

pies

orri

ghts

from

you

unde

rth

isL

icen

se.

Ifyo

urri

ghts

have

been

term

inat

edan

dno

tpe

rman

ently

rein

stat

ed,

re-

ceip

tofa

copy

ofso

me

oral

lof

the

sam

em

ater

iald

oes

notg

ive

you

any

righ

tsto

use

it.10

.FU

-T

UR

ER

EV

ISIO

NS

OF

TH

ISL

ICE

NSE

Page 375: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

The

Free

Soft

war

eFo

unda

tion

may

publ

ish

new

,re

vise

dve

r-si

ons

ofth

eG

NU

Free

Doc

-um

enta

tion

Lic

ense

from

time

totim

e.Su

chne

wve

rsio

nsw

illbe

sim

ilar

insp

irit

toth

epr

esen

tve

rsio

n,bu

tm

aydi

f-fe

rin

deta

ilto

addr

ess

new

prob

lem

sor

conc

erns

.Se

eht

tp://

ww

w.g

nu.o

rg/c

opyl

eft/.

Eac

hve

rsio

nof

the

Lic

ense

isgi

ven

adi

stin

guis

hing

vers

ion

num

ber.

Ifth

eD

ocum

ent

spec

-ifi

esth

ata

part

icul

arnu

mbe

red

vers

ion

ofth

isL

icen

se"o

ran

yla

ter

vers

ion"

appl

ies

toit,

you

have

the

optio

nof

follo

win

gth

ete

rms

and

cond

ition

sei

ther

ofth

atsp

ecifi

edve

rsio

nor

ofan

yla

ter

vers

ion

that

has

been

pub-

lishe

d(n

otas

adr

aft)

byth

eFr

eeSo

ftw

are

Foun

datio

n.If

the

Doc

umen

tdoe

snot

spec

ify

ave

rsio

nnu

mbe

rof

this

Lic

ense

,yo

um

aych

oose

any

vers

ion

ever

publ

ishe

d(n

otas

adr

aft)

byth

eFr

eeSo

ftw

are

Foun

da-

tion.

Ifth

eD

ocum

ents

peci

fies

that

apr

oxy

can

deci

dew

hich

futu

reve

rsio

nsof

this

Lic

ense

can

beus

ed,

that

prox

y’s

pub-

licst

atem

ento

fac

cept

ance

ofa

vers

ion

perm

anen

tlyau

thor

izes

you

toch

oose

that

vers

ion

for

the

Doc

umen

t.11

.R

EL

ICE

NS-

ING

"Mas

sive

Mul

tiaut

hor

Col

-la

bora

tion

Site

"(o

r"M

MC

Site

")m

eans

any

Wor

ldW

ide

Web

serv

erth

atpu

blis

hes

copy

righ

tabl

ew

orks

and

also

prov

ides

prom

inen

tfac

ilitie

sfo

ran

ybod

yto

edit

thos

ew

orks

.A

publ

icw

iki

that

anyb

ody

can

edit

isan

exam

ple

ofsu

cha

serv

er.

A"M

assi

veM

ultia

utho

rC

olla

bora

tion"

(or

"MM

C")

cont

aine

din

the

site

mea

nsan

yse

tof

copy

righ

tabl

ew

orks

thus

publ

ishe

don

the

MM

Csi

te.

"CC

-BY

-SA

"m

eans

the

Cre

-at

ive

Com

mon

sA

ttrib

utio

n-Sh

are

Alik

e3.

0lic

ense

pub-

lishe

dby

Cre

ativ

eC

omm

ons

Cor

pora

tion,

ano

t-fo

r-pr

ofit

corp

orat

ion

with

apr

inci

pal

plac

eof

busi

ness

inSa

nFr

an-

cisc

o,C

alif

orni

a,as

wel

las

futu

reco

pyle

ftve

rsio

nsof

that

licen

sepu

blis

hed

byth

atsa

me

orga

niza

tion.

"Inc

orpo

rate

"m

eans

topu

blis

hor

repu

blis

ha

Doc

umen

t,in

who

leor

inpa

rt,

aspa

rtof

an-

othe

rDoc

umen

t.

An

MM

Cis

"elig

ible

for

re-

licen

sing

"if

itis

licen

sed

un-

der

this

Lic

ense

,an

dif

all

wor

ksth

atw

ere

first

publ

ishe

dun

der

this

Lic

ense

som

ewhe

reot

her

than

this

MM

C,

and

sub-

sequ

ently

inco

rpor

ated

inw

hole

orin

part

into

the

MM

C,

(1)

had

noco

ver

text

sor

inva

rian

tse

ctio

ns,

and

(2)

wer

eth

usin

-co

rpor

ated

prio

rto

Nov

embe

r1,

2008

.

The

oper

ator

ofan

MM

CSi

tem

ayre

publ

ish

anM

MC

con-

tain

edin

the

site

unde

rC

C-B

Y-

SAon

the

sam

esi

teat

any

time

befo

reA

ugus

t1,2

009,

prov

ided

the

MM

Cis

elig

ible

forr

elic

ens-

ing.

AD

DE

ND

UM

:How

tous

eth

isL

icen

sefo

ryou

rdoc

umen

ts

Tous

eth

isL

icen

sein

ado

cu-

men

tyo

uha

vew

ritte

n,in

clud

ea

copy

ofth

eL

icen

sein

the

docu

men

tan

dpu

tth

efo

llow

-in

gco

pyri

ght

and

licen

seno

-tic

esju

staf

tert

hetit

lepa

ge:

Cop

yrig

ht(C

)Y

EA

RY

OU

RN

AM

E.P

erm

issi

onis

gran

ted

toco

py,

dist

ribu

tean

d/or

mod

ify

this

docu

men

tun

der

the

term

sof

the

GN

UFr

eeD

ocum

enta

-tio

nL

icen

se,V

ersi

on1.

3or

any

late

rve

rsio

npu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

datio

n;w

ithno

Inva

rian

tSec

tions

,no

Fron

t-C

over

Text

s,an

dno

Bac

k-C

over

Text

s.A

copy

ofth

elic

ense

isin

clud

edin

the

sect

ion

entit

led

"GN

UFr

eeD

ocum

enta

tion

Li-

cens

e".

Ifyo

uha

veIn

vari

ant

Sect

ions

,Fr

ont-

Cov

erTe

xts

and

Bac

k-C

over

Text

s,re

plac

eth

e"w

ith..

.Te

xts.

"lin

ew

ithth

is:

with

the

Inva

rian

tSe

ctio

nsbe

-in

gL

IST

TH

EIR

TIT

LE

S,w

ithth

eFr

ont-

Cov

erTe

xts

bein

gL

IST,

and

with

the

Bac

k-C

over

Text

sbe

ing

LIS

T.

Ifyo

uha

veIn

vari

ant

Sect

ions

with

out

Cov

erTe

xts,

orso

me

othe

rco

mbi

natio

nof

the

thre

e,m

erge

thos

etw

oal

tern

ativ

esto

suit

the

situ

atio

n.

Ifyo

urdo

cum

ent

cont

ains

non-

triv

ial

exam

ples

ofpr

ogra

mco

de,

we

reco

mm

end

rele

asin

gth

ese

exam

ples

inpa

ralle

lund

eryo

urch

oice

offr

eeso

ftw

are

li-ce

nse,

such

asth

eG

NU

Gen

eral

Publ

icL

icen

se,

tope

rmit

thei

rus

ein

free

soft

war

e.

Page 376: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

36.3

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

GN

UL

ESS

ER

GE

NE

RA

LPU

BL

ICL

ICE

NSE

Ver

sion

3,29

June

2007

Cop

yrig

ht©

2007

Free

Soft

war

eFo

unda

tion,

Inc.

<http

://fs

f.org

/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

nota

llow

ed.

Thi

sve

rsio

nof

the

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

inco

rpo-

rate

sthe

term

sand

cond

ition

sof

vers

ion

3of

the

GN

UG

ener

alPu

blic

Lic

ense

,su

pple

men

ted

byth

ead

ditio

nal

perm

issi

ons

liste

dbe

low

.0.A

dditi

onal

Defi

-ni

tions

.

As

used

here

in,

“thi

sL

icen

se”

refe

rsto

vers

ion

3of

the

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

,an

dth

e“G

NU

GPL

”re

fers

tove

rsio

n3

ofth

eG

NU

Gen

eral

Publ

icL

icen

se.

“The

Lib

rary

”re

fers

toa

cov-

ered

wor

kgo

vern

edby

this

Li-

cens

e,ot

hert

han

anA

pplic

atio

nor

aC

ombi

ned

Wor

kas

defin

edbe

low

.

An

“App

licat

ion”

isan

yw

ork

that

mak

esus

eof

anin

terf

ace

prov

ided

byth

eL

ibra

ry,

but

whi

chis

noto

ther

wis

eba

sed

onth

eL

ibra

ry.D

efini

nga

subc

lass

ofa

clas

sde

fined

byth

eL

ibra

ryis

deem

eda

mod

eof

usin

gan

in-

terf

ace

prov

ided

byth

eL

ibra

ry.

A“C

ombi

ned

Wor

k”is

aw

ork

prod

uced

byco

mbi

ning

orlin

k-in

gan

App

licat

ion

with

the

Li-

brar

y.T

hepa

rtic

ular

vers

ion

ofth

eL

ibra

ryw

ithw

hich

the

Com

-bi

ned

Wor

kw

asm

ade

isal

soca

lled

the

“Lin

ked

Ver

sion

”.

The

“Min

imal

Cor

resp

ond-

ing

Sour

ce”

for

aC

ombi

ned

Wor

km

eans

the

Cor

resp

ondi

ngSo

urce

for

the

Com

bine

dW

ork,

excl

udin

gan

yso

urce

code

for

port

ions

ofth

eC

ombi

ned

Wor

kth

at,c

onsi

dere

din

isol

atio

n,ar

e

base

don

the

App

licat

ion,

and

noto

nth

eL

inke

dV

ersi

on.

The

“Cor

resp

ondi

ngA

pplic

a-tio

nC

ode”

for

aC

ombi

ned

Wor

km

eans

the

obje

ctco

dean

d/or

sour

ceco

defo

rth

eA

p-pl

icat

ion,

incl

udin

gan

yda

taan

dut

ility

prog

ram

sne

eded

for

repr

oduc

ing

the

Com

bine

dW

ork

from

the

App

licat

ion,

but

excl

udin

gth

eSy

stem

Lib

rari

esof

the

Com

bine

dW

ork.

1.E

x-ce

ptio

nto

Sect

ion

3of

the

GN

UG

PL.

You

may

conv

eya

cove

red

wor

kun

der

sect

ions

3an

d4

ofth

isL

icen

sew

ithou

tbei

ngbo

und

byse

ctio

n3

ofth

eG

NU

GPL

.2.

Con

veyi

ngM

odifi

edV

ersi

ons.

Ifyo

um

odif

ya

copy

ofth

eL

ibra

ry,

and,

inyo

urm

odifi

ca-

tions

,afa

cilit

yre

fers

toa

func

-tio

nor

data

tobe

supp

lied

byan

App

licat

ion

that

uses

the

faci

l-ity

(oth

erth

anas

anar

gum

ent

pass

edw

hen

the

faci

lity

isin

-vo

ked)

,the

nyo

um

ayco

nvey

aco

pyof

the

mod

ified

vers

ion:

*a)

unde

rthi

sLic

ense

,pro

vide

dth

atyo

um

ake

ago

odfa

ithef

-fo

rtto

ensu

reth

at,

inth

eev

ent

anA

pplic

atio

ndo

esno

tsu

pply

the

func

tion

orda

ta,

the

faci

l-ity

still

oper

ates

,an

dpe

rfor

ms

wha

teve

rpa

rtof

itspu

rpos

ere

-m

ains

mea

ning

ful,

or*

b)un

-de

rth

eG

NU

GPL

,w

ithno

neof

the

addi

tiona

lper

mis

sion

sof

this

Lic

ense

appl

icab

leto

that

copy

.

3.O

bjec

tC

ode

Inco

rpor

atin

gM

ater

ial

from

Lib

rary

Hea

der

File

s.

The

obje

ctco

defo

rmof

anA

p-pl

icat

ion

may

inco

rpor

ate

mat

e-ri

alfr

oma

head

erfil

eth

atis

part

ofth

eL

ibra

ry.

You

may

conv

eysu

chob

ject

code

unde

rte

rms

ofyo

urch

oice

,pr

ovid

edth

at,i

fthe

inco

rpor

ated

mat

eria

lis

not

limite

dto

num

eric

alpa

-ra

met

ers,

data

stru

ctur

ela

yout

san

dac

cess

ors,

orsm

all

mac

ros,

inlin

efu

nctio

nsan

dte

mpl

ates

(ten

orfe

wer

lines

inle

ngth

),yo

udo

both

ofth

efo

llow

ing:

Page 377: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

*a)

Giv

epr

omin

entn

otic

ew

ithea

chco

pyof

the

obje

ctco

deth

atth

eL

ibra

ryis

used

init

and

that

the

Lib

rary

and

itsus

ear

eco

v-er

edby

this

Lic

ense

.*

b)A

c-co

mpa

nyth

eob

ject

code

with

aco

pyof

the

GN

UG

PLan

dth

islic

ense

docu

men

t.

4.C

ombi

ned

Wor

ks.

You

may

conv

eya

Com

bine

dW

ork

unde

rte

rms

ofyo

urch

oice

that

,ta

ken

toge

ther

,ef

-fe

ctiv

ely

dono

tre

stri

ctm

odi-

ficat

ion

ofth

epo

rtio

nsof

the

Lib

rary

cont

aine

din

the

Com

-bi

ned

Wor

kan

dre

vers

een

-gi

neer

ing

for

debu

ggin

gsu

chm

odifi

catio

ns,

ifyo

ual

sodo

each

ofth

efo

llow

ing:

*a)

Giv

epr

omin

entn

otic

ew

ithea

chco

pyof

the

Com

bine

dW

ork

that

the

Lib

rary

isus

edin

itan

dth

atth

eL

ibra

ryan

dits

use

are

cove

red

byth

isL

i-ce

nse.

*b)

Acc

ompa

nyth

eC

ombi

ned

Wor

kw

itha

copy

ofth

eG

NU

GPL

and

this

licen

sedo

cum

ent.

*c)

For

aC

om-

bine

dW

ork

that

disp

lays

copy

-ri

ght

notic

esdu

ring

exec

utio

n,in

clud

eth

eco

pyri

ghtn

otic

efo

r

the

Lib

rary

amon

gth

ese

notic

es,

asw

ell

asa

refe

renc

edi

rect

ing

the

user

toth

eco

pies

ofth

eG

NU

GPL

and

this

licen

sedo

c-um

ent.

*d)

Do

one

ofth

efo

l-lo

win

g:o

0)C

onve

yth

eM

in-

imal

Cor

resp

ondi

ngSo

urce

un-

der

the

term

sof

this

Lic

ense

,an

dth

eC

orre

spon

ding

App

lica-

tion

Cod

ein

afo

rmsu

itabl

efo

r,an

dun

der

term

sth

atpe

r-m

it,th

eus

erto

reco

mbi

neor

relin

kth

eA

pplic

atio

nw

itha

mod

ified

vers

ion

ofth

eL

inke

dV

ersi

onto

prod

uce

am

odifi

edC

ombi

ned

Wor

k,in

the

man

-ne

rsp

ecifi

edby

sect

ion

6of

the

GN

UG

PLfo

rco

nvey

ing

Cor

resp

ondi

ngSo

urce

.o

1)U

sea

suita

ble

shar

edlib

rary

mec

hani

smfo

rlin

king

with

the

Lib

rary

.A

suita

ble

mec

ha-

nism

ison

eth

at(a

)us

esat

run

time

aco

pyof

the

Lib

rary

alre

ady

pres

ent

onth

eus

er’s

com

pute

rsy

stem

,an

d(b

)w

illop

erat

epr

oper

lyw

itha

mod

i-fie

dve

rsio

nof

the

Lib

rary

that

isin

terf

ace-

com

patib

lew

ithth

eL

inke

dV

ersi

on.*

e)Pr

ovid

eIn

-st

alla

tion

Info

rmat

ion,

but

only

ifyo

uw

ould

othe

rwis

ebe

re-

quir

edto

prov

ide

such

info

r-m

atio

nun

der

sect

ion

6of

the

GN

UG

PL,

and

only

toth

eex

-te

ntth

atsu

chin

form

atio

nis

nec-

essa

ryto

inst

all

and

exec

ute

am

odifi

edve

rsio

nof

the

Com

-bi

ned

Wor

kpr

oduc

edby

reco

m-

bini

ngor

relin

king

the

App

lica-

tion

with

am

odifi

edve

rsio

nof

the

Lin

ked

Ver

sion

.(I

fyo

uus

eop

tion

4d0,

the

Inst

alla

tion

In-

form

atio

nm

ust

acco

mpa

nyth

eM

inim

alC

orre

spon

ding

Sour

cean

dC

orre

spon

ding

App

licat

ion

Cod

e.If

you

use

optio

n4d

1,yo

um

ust

prov

ide

the

Inst

alla

-tio

nIn

form

atio

nin

the

man

ner

spec

ified

byse

ctio

n6

ofth

eG

NU

GPL

forc

onve

ying

Cor

re-

spon

ding

Sour

ce.)

5.C

ombi

ned

Lib

rari

es.

You

may

plac

elib

rary

faci

litie

sth

atar

ea

wor

kba

sed

onth

eL

i-br

ary

side

bysi

dein

asi

ngle

li-br

ary

toge

ther

with

othe

rlib

rary

faci

litie

sth

atar

eno

tA

pplic

a-tio

nsan

dar

eno

tco

vere

dby

this

Lic

ense

,and

conv

eysu

cha

com

bine

dlib

rary

unde

rter

ms

ofyo

urch

oice

,if

you

dobo

thof

the

follo

win

g:

*a)

Acc

ompa

nyth

eco

mbi

ned

libra

ryw

itha

copy

ofth

esa

me

wor

kba

sed

onth

eL

ibra

ry,

un-

com

bine

dw

ithan

yot

herl

ibra

ryfa

cilit

ies,

conv

eyed

unde

rth

ete

rms

ofth

isL

icen

se.

*b)

Giv

epr

omin

ent

notic

ew

ithth

eco

m-

bine

dlib

rary

that

part

ofit

isa

wor

kba

sed

onth

eL

ibra

ry,a

ndex

plai

ning

whe

reto

find

the

ac-

com

pany

ing

unco

mbi

ned

form

ofth

esa

me

wor

k.

6.R

evis

edV

ersi

ons

ofth

eG

NU

Les

serG

ener

alPu

blic

Lic

ense

.

The

Free

Soft

war

eFo

unda

tion

may

publ

ish

revi

sed

and/

orne

wve

rsio

nsof

the

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

from

time

totim

e.Su

chne

wve

rsio

nsw

illbe

sim

ilar

insp

irit

toth

epr

esen

tve

rsio

n,bu

tm

aydi

ffer

inde

tail

toad

dres

sne

wpr

ob-

lem

sor

conc

erns

.

Eac

hve

rsio

nis

give

na

dist

in-

guis

hing

vers

ion

num

ber.

Ifth

eL

ibra

ryas

you

rece

ived

itsp

eci-

fies

that

ace

rtai

nnu

mbe

red

ver-

sion

ofth

eG

NU

Les

serG

ener

alPu

blic

Lic

ense

“ora

nyla

terv

er-

sion

”ap

plie

sto

it,yo

uha

veth

eop

tion

offo

llow

ing

the

term

san

dco

nditi

ons

eith

erof

that

publ

ishe

dve

rsio

nor

ofan

yla

ter

Page 378: ogramming - Wikimedia · 124 125 139 151 155 165 165 174 181 184 187 189 227 235 236 241 246 247 248

vers

ion

publ

ishe

dby

the

Free

Soft

war

eFo

unda

tion.

Ifth

eL

i-br

ary

asyo

ure

ceiv

edit

does

not

spec

ify

ave

rsio

nnu

mbe

rof

the

GN

UL

esse

rG

ener

alPu

blic

Li-

cens

e,yo

um

aych

oose

any

ver-

sion

ofth

eG

NU

Les

serG

ener

alPu

blic

Lic

ense

ever

publ

ishe

dby

the

Free

Soft

war

eFo

unda

-tio

n.

Ifth

eL

ibra

ryas

you

rece

ived

itsp

ecifi

esth

ata

prox

yca

nde

-ci

dew

heth

erfu

ture

vers

ions

ofth

eG

NU

Les

ser

Gen

eral

Publ

icL

icen

sesh

alla

pply

,tha

tpro

xy’s

publ

icst

atem

ent

ofac

cept

ance

ofan

yve

rsio

nis

perm

anen

tau-

thor

izat

ion

for

you

toch

oose

that

vers

ion

fort

heL

ibra

ry.