+ All Categories
Home > Documents > python3.odp

python3.odp

Date post: 26-Feb-2018
Category:
Upload: raedadobeadobe
View: 222 times
Download: 0 times
Share this document with a friend

of 459

Transcript
  • 7/25/2019 python3.odp

    1/458

    1

    An introduction to Pythonfor absolute beginners

    http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB

    Bob Dowling

    ni!ersity "nformation #er!icesscientific-computing$ucs.cam.ac.uk

  • 7/25/2019 python3.odp

    2/458

    2

    But first%

    &ire escapes

    'o drinks or snacksin the room( please.

    )oilets

    'otes

    #igning in&eedback

  • 7/25/2019 python3.odp

    3/458

    3

    *ourse outline + ,

    ho uses Python what forhat sort of language it is

    ow to launch Python

    Python scripts

    0eading in user data

    'umbers*on!ersions*omparisons

    'ames for !alues)ext

    )ruth &alsehood

  • 7/25/2019 python3.odp

    4/458

    4

    *ourse outline + 1

    Assignment'ames

    2ur first 3real4 program

    5oopsif% else%

    "ndentation

    *omments

  • 7/25/2019 python3.odp

    5/458

    5

    *ourse outline + 6

    Lists"ndices5engths*hanging items

    7xtending lists8ethods

    *reating lists)esting lists

    0emo!ing from lists

    for% loop

    "terables#lices

  • 7/25/2019 python3.odp

    6/458

    6

    *ourse outline + 9

    Files0eading writing

    riting our own functions

    )uples

    8odules#ystem modules

    7xternal modules

    Dictionaries

    &ormatted text

  • 7/25/2019 python3.odp

    7/458

    7

    ho uses Python

    2n-line games

    eb ser!ices

    Applications

    #cience

    "nstrument control

    7mbedded systems

    en.wikipedia.org/wiki/List_of_Python_software

  • 7/25/2019 python3.odp

    8/458

    8

    hat sort of language is Python

    7xplicitly

    compiledto machinecode

    Purely

    interpreted

    *( *;;(&ortran #hell(Perl

    7xplicitly

    compiledto bytecode

  • 7/25/2019 python3.odp

    9/458

    9

    0unning Python + ,

  • 7/25/2019 python3.odp

    10/458

    10

    0unning Python + 1

    $ python3

    nix prompt

    nix command

    "ntroductory blurb

    Python prompt

    [GCC 4.6.3] on lin!"#defalt %ay 3 "&'" '()(4)4"*

    Python !ersion

    Python 3.".3

    +++

  • 7/25/2019 python3.odp

    11/458

    11

    >uitting Python

    +++ exit()

    +++ quit()

    +++ *trl D;

    Any oneof these

  • 7/25/2019 python3.odp

    12/458

    12

    A first Python command

    +++ print('Hello, world!')

    ,ello world-

    +++

    Python prompt

    Python command

    2utput

    Python prompt

  • 7/25/2019 python3.odp

    13/458

    13

    Python commands

    print

    Python 3function4

    (

    &unction?s 3argument4

    0ound brackets+ 3parentheses4

    ( )'Hello, world!'

    3*ase sensiti!e4print PRINT

  • 7/25/2019 python3.odp

    14/458

  • 7/25/2019 python3.odp

    15/458

    15

    >uotes

    print *ommand

    print )ext

  • 7/25/2019 python3.odp

    16/458

    16

    Alternati!e Pythons

    iPython

    idle

  • 7/25/2019 python3.odp

    17/458

    17

    Python scripts

    hello'.py

    &ile in home directory

    $ python3

    ,ello world-

    $

    nix prompt

    nix commandto run Python

    Python script

    Python script?s output

    nix prompt

    hello1.py

    print#,ello world-*

    0un from Unixprompt

  • 7/25/2019 python3.odp

    18/458

    18

    7diting Python scripts ,

  • 7/25/2019 python3.odp

    19/458

  • 7/25/2019 python3.odp

    20/458

    20

    Progress

    "nteracti!e Python

    Python scripts

    print#*command

    #imple Python text

  • 7/25/2019 python3.odp

    21/458

    21

    7xercise ,

    ,. Print 3oodbye( cruel worldC4 from interacti!e Python.

    1. 7dit e!erise'.pyto print the same text.

    6. 0un the modified e!erise'.pyscript.

    1 minutes

    Please ask if you ha!e @uestions.

  • 7/25/2019 python3.odp

    22/458

    22

    A little more text

    hello".py

    print# 01 2 5*&ull 3nicode4 support

    www.niode.org/harts/

  • 7/25/2019 python3.odp

    23/458

    23

    etting characters

    Altr #hift; =; g

    35A)"' #8A55

    57))70 ") B07E74 7&''f

    *haracter #elector

    5inux

    F

  • 7/25/2019 python3.odp

    24/458

    24

    )ext: a 3string4 of characters

    +++ type('Hello, world!')

    8lass str+ A string of characters

    , e l l o w o r l d -'3

    *lass: string

    5ength: ,6

    5etters

    str

  • 7/25/2019 python3.odp

    25/458

    25

    )ext: 3behind the scenes4

    str '3 9" '&' '&: '&: ''' 44 3" 33'&&;

    &''f'6

    >

    #pecial 2rdinary

    7n

    7t

    2rdinary #pecial

  • 7/25/2019 python3.odp

    36/458

    36

    7n: unwieldy for long text

    AEFHB IHBLJKBM Nr. Liesey and the7nrest of these gentleOen haing asked Oe7nto write down the whole partilars7naot Ireasre sland froO the7neginning tothe end keeping nothing7nak t the

    earings of the island7nand that only ease there is still7ntreasre not yet lifted take p Oy7npen in the year of grae '9__ and go7nak to the tiOe when Oyfather kept7nthe JdOiral Qenow inn and t

    he rown7nold seaOan with the sare t first7ntook p his lodging nder or roof.

    #ingleline

  • 7/25/2019 python3.odp

    37/458

    37

    #pecial input method for long text

    Triple@uotes

    rest of these gentleOen haing asked Oeto write down the whole partilarsaot Ireasre sland froO theeginning to the end keeping nothing

    ak t the earings of the islandand that only ease there is stilltreasre not yet lifted take p Oypen in the year of grae '9__ and goak to the tiOe when Oy father kept

    the JdOiral Qenow inn and the rownold seaOan with the sare t firsttook p his lodging nder or roof.

    AEFHB IHBLJKBM Nr. Liesey and the

    8ultiplelines

  • 7/25/2019 python3.odp

    38/458

    38

    Python?s 3secondary4 prompt

    +++ '''Hello,world'''...

    Python asking for more

    of the same command.

  • 7/25/2019 python3.odp

    39/458

    39

    "t?s still Gust textC

    +++ 'Hello,%nworld!'

    ,ello

    +++

    ...

    '''Hello,

    world!'''

    ,ello7nworld

    world7n

    Python uses Hn to representline breaks in strings.

    Exactlythe sameC

    h i f i

  • 7/25/2019 python3.odp

    40/458

    40

    Iour choice of input @uotes:

    ,ello7nworld- >,ello7nworld->

    >>>,elloworld->>>

    ,elloworld-

    str '3 e l l o w o r l d -,

    #ame result:

    &our inputs:

    P

  • 7/25/2019 python3.odp

    41/458

    41

    Progress

    "nternational text

    print#*

    *oncatenation of strings

    5ong strings

    #pecial characters

    7 i 1

  • 7/25/2019 python3.odp

    42/458

    42

    7xercise 1

    6 minutes

    ,. 0eplace JJJJin e!erise".pyso it prints the followingtext Kwith the line breaksL and then run the script.

    coffeeMaffeecafNcaffO

    N

    O 7&&e:

    7&&eR

    Altr

    Altr

    ;

    ;

    =

    e

    e

    Att hi t l

  • 7/25/2019 python3.odp

    43/458

    43

    Attaching names to !alues

    Oessage S ,ello world-print#Oessage*

    hello3.py

    str '3 e l l o w o r l d -,Oessage

    3!ariables4

    +++ e**+-e'Hello, world!'

    +++ e**+-e

    ,ello world-

    +++ type(e**+-e)

    8lass str+

    Att hi t l

  • 7/25/2019 python3.odp

    44/458

    44

    Attaching names to !alues

    Oessage S ,ello world-print#Oessage*

    hello4.py

    print function

    str '3 e l l o w o r l d -,Oessage

    +++ type(print)

    8lass iltin_fntion_or_Oethod+

    0 di t t i t i t

  • 7/25/2019 python3.odp

    45/458

    45

    0eading some text into a script

    $ python3

    MesT

    input1.py

    Qoo-

    /oo!

    Oessage S inpt#MesT*

    print#Oessage*

    inpt'.py

    inpt#MesT*

    Oessage S ;

    print#Oessage*

    *anQt read numbers directlyC

  • 7/25/2019 python3.odp

    46/458

    46

    *anQt read numbers directlyC

    nOer S inpt#T*

    print#nOer = '*

    inpt".py

    $ python3 input.py

    T 1&

    Iraeak #Oost reent all last*) ?ile >inpt".py> line " in 8Oodle+

    print# = *

    string integer

    nOer

    IypeBrror)Cant onert int oUetto str iOpliitly

    '

    inpt#*: strings only

  • 7/25/2019 python3.odp

    47/458

    47

    inpt#*: strings only

    nOer S inpt#T*

    print#nOer = '*

    inpt".py

    $ python3 input.py

    T 1&

    inpt#T * str " &'

    int '&R

    #ome more types

  • 7/25/2019 python3.odp

    48/458

    48

    #ome more types

    +++ type('Hello, world!')

    8lass str+

    +++ type(0)

    8lass int+

    +++ type(3.1012)

    8lass float+

    string of characters

    integer

    floating point number

    *on!erting text to integers

  • 7/25/2019 python3.odp

    49/458

    49

    *on!erting text to integers

    +++ int('1&')

    '&

    +++ int('1&&')

    V'&&

    +++ int('1&&1&')

    WaleBrror)inalid literal for int#* with ase '&) '&&V'&

    str " &' int '&

    str 6 V

    int V'&&

    &' &

    *on!erting text to floats

  • 7/25/2019 python3.odp

    50/458

    50

    *on!erting text to floats

    +++ lo+t('1&.&')

    '&.&

    +++ lo+t('1&.')

    '&.&

    Q,S.SQ is a string

    ,S.S is a floatingpoint number

    *on!erting between ints and floats

  • 7/25/2019 python3.odp

    51/458

    51

    *on!erting between ints and floats

    +++ lo+t(1&)

    '&.&

    +++ int(1&.2)

    '& )runcatesfractional part

    +++ int(1&.2)

    V'&

    *on!erting into text

  • 7/25/2019 python3.odp

    52/458

    52

    *on!erting into text

    +++ *tr(1&)

    '&

    +++ *tr(1&.&&&)

    '&.&

    integer

    float

    string

    string

    *on!erting between types

  • 7/25/2019 python3.odp

    53/458

    53

    *on!erting between types

    int#*

    float#*

    anything

    anything

    integer

    float

    str#* anything string

    &unctions named after the type they con!ert into.

    0eading numbers into a script

  • 7/25/2019 python3.odp

    54/458

    54

    0eading numbers into a script

    te!t S inpt#T *

    nOer S int#te!t*print#nOer = '*$

    T

    ''

    python3 input3.py

    1&

    #tepping through our script ,

  • 7/25/2019 python3.odp

    55/458

    55

    #tepping through our script ,

    te!t S inpt#T*

    nOer S int#te!t*print#nOer = '*

    str 3 T

    #tepping through our script 1

  • 7/25/2019 python3.odp

    56/458

    56

    #tepping through our script 1

    te!t S inpt#T*

    nOer S int#te!t*print#nOer = '*

    str 3 T

    inpt function

    str " &' 'B: text( not number

    #tepping through our script 6

  • 7/25/2019 python3.odp

    57/458

    57

    #tepping through our script 6

    te!t Sinpt#T *

    nOer S int#te!t*print#nOer = '*

    inpt function

    str " &'te!t

    #tepping through our script 9

  • 7/25/2019 python3.odp

    58/458

    58

    #tepping through our script 9

    te!t S inpt#T *

    nOer S int#te!t*print#nOer = '*

    inpt function

    str " &'te!t

    int function

    int '&

    #tepping through our script T

  • 7/25/2019 python3.odp

    59/458

    59

    #tepping through our script T

    te!t S inpt#T *

    nOer S int#te!t*print#nOer = '*

    inpt function

    str " &'te!t

    int function

    int '&nOer

    #tepping through our script U

  • 7/25/2019 python3.odp

    60/458

    60

    #tepping through our script U

    te!t S inpt#T *

    nOer Sint#te!t*print#nOer = '*

    int '&nOer

    #tepping through our script V

  • 7/25/2019 python3.odp

    61/458

    61

    #tepp g t oug ou sc pt

    te!t S inpt#T *

    nOer S int#te!t*print#nOer = '*

    int '&nOer

    function

    int ''

    =

    int '

    #tepping through our script U

  • 7/25/2019 python3.odp

    62/458

    62

    pp g g p

    te!t S inpt#T *

    nOer S int#te!t*print#nOer = '*

    int '&nOer

    int ''

    functionprint

    Progress

  • 7/25/2019 python3.odp

    63/458

    63

    g

    'ames

    )ypes

    )ype con!ersions

    Ealues

    0eading in text

    str#* int#* float#*

    inpt#prompt*

    nameS value

    strings

    integers

    floating point numbers

    7xercise 6

  • 7/25/2019 python3.odp

    64/458

    64

    0eplace the two JJJJin exercise6.pyto do the following:

    ,. Prompt the user with the text 3ow much4.

    1. *on!ert the user?s answer to a floating point number.

    6. Print 1.T plus that number.

    6 minutes

    "ntegers

  • 7/25/2019 python3.odp

    65/458

    65

    g

    W% -1( -,( S(,( 1( 6( 9 %X

    "nteger addition subtraction

  • 7/25/2019 python3.odp

    66/458

    66

    g

    +++ &

    "(

    +++ &

    '(

    #paces around theoperator don?t matter.

    3'o surprises4

    "nteger multiplication

  • 7/25/2019 python3.odp

    67/458

    67

    )here is no 3Y4 on the keyboard. 5inux:(;#hiftAltr ;

    se 3X4 instead

    +++ &4

    '&&

    #till no surprises

    "nteger di!ision

  • 7/25/2019 python3.odp

    68/458

    68

    )here is no 3Z4 on the keyboard. 5inux:.;#hiftAltr ;

    se 3/4 instead

    +++ &5

    4.& )his is a floating point numberC

    #urpriseC

    "nteger di!ision gi!es floats C

    C

  • 7/25/2019 python3.odp

    69/458

    69

    &ractions

    +++ &50&

    &.(

    +++ &53&

    &.6666666666666666

    &loats sometimes

    *onsistency &loats always

    C

    "nteger di!ision gi!es floats C

    C

  • 7/25/2019 python3.odp

    70/458

    70

    +++ &550

    (

    C// #pecial operation to stick with integers

    +++ 1550

    (+++ 1550

    V6

    +++ &50

    (.&

    +++ 150

    (."(+++ 150

    V(."(

    "nteger powers

  • 7/25/2019 python3.odp

    71/458

    71

    )here is no 3914 on the keyboard.

    se 3XX4 instead

    +++ 044

    '6

    +++ 044

    Aynta!Brror) inalid synta!

    #paces aroundtheoperator don?t matter.

    #paces inthe

    operator doC

    "nteger remainders

  • 7/25/2019 python3.odp

    72/458

    72

    e.g. "s a number e!en or odd

    +++ 06

    &

    +++ 6

    '

    se 3Y4

    +++ 6

    ' 0emainder is always non-negati!e

    ow big can a Python integer be

  • 7/25/2019 python3.odp

    73/458

    73

    +++ 44

    4

    +++ 044'6

    +++ 1744"(6

    +++ 7446((36

    +++ 73744

    4"R4R69"R6

    +++ 7446((36

    +++ 7446((36

    +++ 44

    4

    ow big can a Python integer be

  • 7/25/2019 python3.odp

    74/458

    74

    +++ 02027#2744

    ':446944&939&R(('6'6

    +++ 1"007#00#&2171744

    34&":"366R"&R3:4634633946&943'96:"''4(6

    +++ 30&"3772&23"0730733#07#7"110744''(9R"&:R"393'6'R(4"3(9&R:(&&:6:9R&9:(3"6RR:466(64&(64&3R4(9(:4&&9R'3'"R63RR36

    +++ 11#2&"23#3171203#&2"&&"7"#2"372

    '34&9:&9R"RR4"(R9&RR(94&"4RR:"&(:46'"949R36(:"&(R"3R33999"3(6'4439"'964&3&&93(46R96:&':94"R:'66R&34"96R&&3':(:':64:6&(&:(39(3::":''R46(6RR4643364R&&6&:4&R6

    2"07770&70&320#"0&

    ow big can a Python integer be

  • 7/25/2019 python3.odp

    75/458

    75

    ,S996[[[[,9,6,T1TSUU\,VT1V,SV,UU196[1TV\\U919\S9V6[6V[S6[91669[61[6\T6\SV\V,TTV9TU[9[[1U[,,\69\\VTT[69S[\S,SUV,996\1U1[6V\[VTV696[,[TV\6USV1U616US[V[T,6UT1VV\9T\TU\VUT96VS\\\[69S6U,T\S,696[6V,[6,991[SVSS,,[TT\9U11U6VU6,[[6\6\VV,1V9TUV1669U[9699T[UU,V9\U[SV\S[VST[S6VS9SV,1[9S9[V9S,,[US\,,99UV\VVV[6T\[S1\SSUU[U\6[\VU[[,V[VV[T\9U\STU6S,\S1US\9ST\\TV\9T6961[169U\6S6S1UU\U996ST\S1TS,T\V16\\[UVV,91,TT9,U\6[6TTT\[[T1\,9[U6,[16V\,99699\UV69S[V[,,[V1U6\9\U9VT,SS,[\S9,69\SS[9,VSU,U

    VTS\6UU[666[TSTT,S61\V1S[[1U\TTSVU\\[6U,U6U\9,,\66S,T1,6V\U[1T[6V,[[S\,[66UTUVT,11,6,[9\1[9U6U[,1TTTS11T\\[6SS9,1699V[9[U1T\TUV99\1,\9U,VS16[SUTST\,619TU,S[1TV6,[6T6[SS[VUS[U11,S1[691VS,\VU\[1S16,6,U\S,VUV[SSUUVT,\T9[TSV\\1,U6U9,\6VS1[T6VT,19V[9S,9\SV,T\,6T9T\\[1V\ST,66\\U,,TT,V\91V,,SU[6,,69S\ST[91V1[[91V\V\,TT9[9\V[1\T9616T69T,VSUT1161U\SU,6\9\ST\[VU\6SS1,11\U66\TU[VV[1[V[\9[99SU,USSV9,1\9TUV9\,\[16STSTV,U916VV,T9[,U61,6[SU6,S9T\S1\,U,6U\1UVS[691[TU99SV6S99V[\\\V,\S,V[,

    9UTVU69V6116[TS1UV1T6ST\[\\V\T\\US\SV\\9U\1S,VV9U19[,VV,[99\[UV9TTUT\1TS,V[61\SVS9V6,,\966,UTTTS[SVTU[11,[9UTV,V9U6V61\U[[9\,1[,\T1S6,V9TVSS199S\1UU,U\,S[V9,9[6[TSV[9,,\1\[S9T11\[,[TV66[\VVU9[,S6,1US[T\S6SS,6S19,69UV,[\V1UUV61,U9\,T,,,6,US1\1SV[,V6[S6696US\S196[S9VS[69S9S6,T9,\S66U

    )here is no limitC

    7xcept formachinememory

    Big integers

  • 7/25/2019 python3.odp

    76/458

    76

    1

    9

    ,U

    1TU

    UTT6U

    91\9\UV1\U

    ,[99UV99SV6VS\TT,U,U

    69S1[16UU\1S\6[9U69%U66V9USV96,VU[1,,9TU

    * / *;;&ortran

    2ut of the reachof * or &ortranC

    long long"')770],U

    long"')770][

    int

    "')770]9

    &loating point numbers

  • 7/25/2019 python3.odp

    77/458

    77

    ,.S

    S.66666666

    6.,9,T\1UT1.V,[1[,[1

    Basic operations

  • 7/25/2019 python3.odp

    78/458

    78

    +++ &.& .&"(.&

    +++ &.& .&'(.&

    +++ &.& 4 .&

    '&&.&

    +++ &.& 5 .&

    4.&

    +++ &.& 44 .&

    3"&&&&&.&

    7@ui!alent to integer arithmetic

    &loating point imprecision

  • 7/25/2019 python3.odp

    79/458

    79

    +++ 1.& 5 3.&&.3333333333333333

    +++ 1&.& 5 3.&

    3.333333333333333(

    ^ 17significant figures

    "f you are relying onthis last decimal place(you are doing it wrongC

    idden imprecisionC

  • 7/25/2019 python3.odp

    80/458

    80

    +++ &.1&.'

    +++ &.1 &.1

    &."

    +++ &.1 &.1 &.1

    &.3&&&&&&&&&&&&&&&40eally: if you are relying onthis last decimal place(you are doing it wrongC

    C

    ow big can a Python float be + ,

  • 7/25/2019 python3.odp

    81/458

    81

    +++ 737.&444"R4R69"R6.&

    +++ 02027#27.&44

    '.:446944&939&R(("e='R

    #o far( so good.

    #witch to

    3scientific notation4

    ,.[99UV99SV6VS\TT1

    ,.[99UV99SV6VS\TT1

    Y,S,\

    e;,\

    &loats are not exact

  • 7/25/2019 python3.odp

    82/458

    82

    +++ 02027#2744

    ':446944&939&R(('6'6

    +++ 02027#27.&44'.:446944&939&R(("e='R

    "nteger

    &loating point

    ,.[99UV99SV6VS\TT1Y,S,\ ,[99UV99SV6VS\TT1SSS

    ,[99UV99SV6VS\TT,U,U-

    6[9

    ow big can a Python float be + 1

  • 7/25/2019 python3.odp

    83/458

    83

    +++ 1."007#00#&2e12443.4&":"366R"&R3:(e=3:

    +++ 3.0&"3772&23"e3"44

    '.'(9R"&:R"393'6"e=99

    +++ 1.1#2&"23#317e##44

    '.34&9:&9R"RR4"(R9e='(4

    +++ 1.30"#e1044

    DerflowBrror) #34Oerial reslt ot of range*

    #o far( so good.

    )oo bigC

    &loating point limits

  • 7/25/2019 python3.odp

    84/458

    84

    '."34(69:R&'"34(69Z'&

    ,V significant figures

    -61T _ ' _ 6S[

    9.\9SUTU9T[9,Y,S-619_ ' _ [.\[[9UTUV96,Y,S6SV

    Positi!e !alues:

    *omplex numbers

  • 7/25/2019 python3.odp

    85/458

    85

    z

    z2

    +++ (1.&.8)44

    #'.3'"(='."(U*

    Progress

  • 7/25/2019 python3.odp

    86/458

    86

    Arithmetic

    "ntegers

    &loating point numbers

    *omplex numbers

    = V X / XX Y

    'o limitsC

    5imited si`e

    5imited precision

    7xercise 9

  • 7/25/2019 python3.odp

    87/458

    87

    6 minutes

    0eplace the JJJJin e!erise4.pyto e!aluateand print out the following calculations:

    ,. 116 Z V,

    1. K, ; ,/,SSL,SS

    6. K, ; ,/,SSSSL,SSSS

    9. K, ; ,/,SSSSSSL,SSSSSS

    'ote: Brackets work inPython arithmetic Gust like theydo in normal mathematics.

    *omparisons

  • 7/25/2019 python3.odp

    88/458

    88

    T _ ,S

    T ,S

    *omparisons

  • 7/25/2019 python3.odp

    89/458

    89

    +++ 9 1&

    Ire

    +++ : 1&

    ?alse

    Asking the @uestion

    Asking the @uestion

    )rue &alse

  • 7/25/2019 python3.odp

    90/458

    90

    +++ type(True)8lass ool+ 3Booleans4

    T ,S;

    T ,S_

    int int

    ,T

    )rue

    int

    bool

    )rue &alse

  • 7/25/2019 python3.odp

    91/458

    91

    bool

    bool

    Ire

    ?alse

    2nly two !alues

    #ix comparisons

  • 7/25/2019 python3.odp

    92/458

    92

    8aths

    =

    Python

    SS

    -S

    8

    +

    8S

    +S

    Doublee@uals sign

    7@uality comparison assignment

  • 7/25/2019 python3.odp

    93/458

    93

    naOeS ale

    S

    ale'SS ale

    "

    SS

    Attach a name to a !alue.

    *ompare two !alues

    )extual comparisons

  • 7/25/2019 python3.odp

    94/458

    94

    +++ '+t' 9 'do-'

    Ire

    Alphabetic ordering

    +++ ';+t' 9 '+t'

    Ire

    +++ '

  • 7/25/2019 python3.odp

    95/458

    95

    erman:

    #wedish:

    ` _

    _ `

    Python ine@ualities use nicode character numbers.

    )his is o!er-simplistic for 3real4 use.

    Alphabetical order

    3*ollation4 is a whole field of computing in itself

    3#yntactic sugar4

  • 7/25/2019 python3.odp

    96/458

    96

    & 8 nOer 8 '&

    & 8 nOer

    and

    nOer 8 '&

    +++ nu=er

    +++ & 9 nu=er 9 1&

    Ire

    *on!erting to booleans

  • 7/25/2019 python3.odp

    97/458

    97

    float#* *on!erts to floating point numbers

    int#* *on!erts to integers

    str#* *on!erts to strings

    =ool#* *on!erts to booleans

    8lass float+

    8lass int+

    8lass str+

    8lass ool+

    seful con!ersions

  • 7/25/2019 python3.odp

    98/458

    98

    ?red Ire

    ?alse

    'on-empty string

    7mpty string

    ' Ire

    & ?alse

    'on-`ero

    ero

    '" Ire

    V' Ire

    Boolean operations

  • 7/25/2019 python3.odp

    99/458

    99

    'umbers ha!e ;( ( ]%

    hat do booleans ha!e

    bool

    bool

    bool

    bool

    bool

    Boolean operations + 3and4

  • 7/25/2019 python3.odp

    100/458

    100

    bool

    bool

    booland

    Ire Ireand

    Ire ?alseand

    ?alse Ireand

    ?alse ?alseand

    Ire

    ?alse

    ?alse

    ?alse

    Both ha!eto be )rue

    Boolean operations + 3and4

  • 7/25/2019 python3.odp

    101/458

    101

    +++ 0 9 +nd 7 9 #

    Ire

    4 8 (

    6 8 9

    Ire

    Ire

    and Ire

    +++ 0 9 +nd 7 : #

    ?alse

    4 8 (

    6 + 9

    Ire

    ?alseand ?alse

    Boolean operations + 3or4

    b l

  • 7/25/2019 python3.odp

    102/458

    102

    bool

    bool

    boolor

    Ire Ireor

    Ire ?alse

    ?alse Ire

    ?alse ?alse

    Ire

    ?alse

    Ire

    Ire

    At leastone hasto be )rueor

    or

    or

    Boolean operations + 3or4

  • 7/25/2019 python3.odp

    103/458

    103

    +++ 0 9 or 7 9 #

    Ire

    4 8 (

    6 8 9

    Ire

    Ire

    or Ire

    +++ 0 9 or 7 : #

    Ire

    4 8 (

    6 + 9

    Ire

    ?alse or Ire

    Boolean operations + 3not4

  • 7/25/2019 python3.odp

    104/458

    104

    bool boolnot

    Irenot

    ?alse Ire

    ?alse

    not

    Boolean operations + 3not4

  • 7/25/2019 python3.odp

    105/458

    105

    +++ not 7 9 #

    ?alse

    6 8 9 Ire not ?alse

    +++ not 7 : #

    Ire

    6 + 9 ?alse not Ire

    Ambiguity in expressions

  • 7/25/2019 python3.odp

    106/458

    106

    6 ; U / 6

    K6 ; UL / 6 6 ; KU / 6L

    6 T

    Di!ision before addition

  • 7/25/2019 python3.odp

    107/458

    107

    T

    6 U / 6;

    6 1;

    Di!ision first

    Addition second

    32rder of precedence4

  • 7/25/2019 python3.odp

    108/458

    108

    !44y !4y!5y!6y !y!y!!

    !y !:y!:y!!y !9y!9y

    not! ! or y! +nd y

    &irst

    5ast

    Progress

    *omparisons SS -S 8 + 8S +S

  • 7/25/2019 python3.odp

    109/458

    109

    *omparisons - 8 + 8 +

    Booleans Ire ?alse

    'umerical comparison

    Alphabetical ordering

    ( 8 9

    dig 8 dg

    Boolean operators and or not

    *on!ersions &

    &.&

    ?alse

    ?alse

    ?alse

    other Ire

    7xercise T

    Predict whether these expressions will e!aluate to Ire or ?alse

  • 7/25/2019 python3.odp

    110/458

    110

    6 minutes

    Predict whether these expressions will e!aluate to Ireor ?alse.)hen try them.

    dog + Cat or 4( Y 3 SS &

    sparrow + eagle

    6& V 4( / ( = '& SS '

    ,.

    1.

    6.

    'ames and !alues: 3assignment4

  • 7/25/2019 python3.odp

    111/458

    111

    +++ +lph+ 1&&

    ,.+lph+ 1&&

    1. +lph+ 1&&

    int '&& Python createsan 3integer ,SS4in memory.

    int '&&alpha

    Python attachesthe name 3alpha4to the !alue.

    Assignment: right to left

  • 7/25/2019 python3.odp

    112/458

    112

    +lph+ 1&&

    30#4: right hand side

    7!aluated first

    35#4: left hand sideProcessed second

    #imple e!aluations

    +++ =et+ 1&& &

  • 7/25/2019 python3.odp

    113/458

    113

    +++ =et+ 1&& &

    0#,. 1&& &

    int '&& function = int "&

    int '"&1.

    int '"&6. eta

    5#

    *hanging !alue ,

    +++ -++ 1

  • 7/25/2019 python3.odp

    114/458

    114

    -++ 1

    +++ -++

    *hanging !alue 1

    +++ -++ 1

    0#

  • 7/25/2019 python3.odp

    115/458

    115

    -int '

    *hanging !alue 6

    +++ -++ 1

    5#

  • 7/25/2019 python3.odp

    116/458

    116

    -

    int 'gaOOa

    *hanging !alue 9

    +++ -++ 1

    0#

  • 7/25/2019 python3.odp

    117/458

    117

    -

    +++ -++ int 'gaOOa

    int "

    *hanging !alue T

    +++ -++ 1

    5#

  • 7/25/2019 python3.odp

    118/458

    118

    -

    +++ -++ int 'gaOOa

    int "

    *hanging !alue U

    +++ -++ 1

    garbage collection

  • 7/25/2019 python3.odp

    119/458

    119

    +++ -++ int 'gaOOa

    int "

    *hanging !alue V

    +++ -++ 1

  • 7/25/2019 python3.odp

    120/458

    120

    +++ -++ gaOOa

    int "

    *hanging !alue a subtlety

    +++ -++ 1

  • 7/25/2019 python3.odp

    121/458

    121

    +++ -++ gaOOa

    int "

    int '

    )wo separate

    integer obGects.

    Python doesn?t change an integer?s !aluePython replacesthe integer.

    Python integers are 3immutable4

    'ames on the 0# ,

    +++ delt+ +lph+ 0&

  • 7/25/2019 python3.odp

    122/458

    122

    0#,.

    +lph+ 0&

    function = int 4&int '&&

    alpha

    int '4&

    1.

    6.

    'ames on the 0# 1

    +++ delt+ +lph+ 0&

  • 7/25/2019 python3.odp

    123/458

    123

    5#9. delta int '4&

    #ame name on both sides S

  • 7/25/2019 python3.odp

    124/458

    124

    delta int '4& #tartingposition

    +++ print(delt+)

    '4&

    #ame name on both sides ,

    +++ delt+ delt+ 1&0#

  • 7/25/2019 python3.odp

    125/458

    125

    ,. delt+ 1&

    function = int '&int '4&

    delta

    int '(&

    1.

    6.

    9.

    #ame name on both sides 1

    +++ delt+ delt+ 1&5#

  • 7/25/2019 python3.odp

    126/458

    126

    T.

    U.

    int '(&

    int '4&delta

    0#

    int '(&

    int '4&delta

    0#

    #ame name on both sides 6

    +++ delt+ delt+ 1&5#

  • 7/25/2019 python3.odp

    127/458

    127

    V.

    [. int '(&delta

    int '(&

    int '4&delta 'o longer

    used.

    3#yntactic sugar4

    thing =S '& thing S thing = '&

  • 7/25/2019 python3.odp

    128/458

    128

    thing =S '& thing S thing ='&

    thing VS '& thing S thing V'&

    thing XS '& thing S thing X'&

    thing /S '& thing S thing /'&

    thing XXS '& thing S thing XX'&

    thing YS '& thing S thing Y'&

    is e@ui!alent to

    Deleting a name + ,

    +++ print(thin-)

  • 7/25/2019 python3.odp

    129/458

    129

    +++ print(thin-)

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+

    +++ thin- 1

    +++ print(thin-)

    '

    aOeBrror) naOe thing is not defined

    nknown!ariable

    Deleting a name + 1

    +++ print(thin-)

  • 7/25/2019 python3.odp

    130/458

    130

    +++ print(thin-)

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+

    +++ del thin-

    +++ print(thin-)

    '

    aOeBrror) naOe thing is not defined

    nknown!ariable

    Mnown!ariable

    Progress

  • 7/25/2019 python3.odp

    131/458

    131

    Assignment

    #trictly right to left

    ; etc. 3syntactic sugar4

    thing S thing = '&

    thing S thing = '&

    1nd ,st

    thing =S '&

    Deletion del thing

    2ur first 3real4 program

    $ python3 *qrt py e ha!e to write srt py

  • 7/25/2019 python3.odp

    132/458

    132

    '.4'4"'3(6"393&R(

    $OerTpython3 *qrt.py

    .&e ha!e to write srt.py

    &irst( the maths.)hen( the Python.

    #@uare root of 1.Sby 3bisection4

    S S too small for 1

  • 7/25/2019 python3.odp

    133/458

    133

    3"nter!al of uncertainty4

    S.S too small for 1

    1.S too large for 1

    S.S _ 1 _ 1.S

    #@uare root of 1.Sby bisection ,

    #& & = " &* / " &

  • 7/25/2019 python3.odp

    134/458

    134

    8id-point: ,.S

    #&.&= ".&* / ".&

    '.&

    '.&XX"

    '.&

    #@uare root of 1.Sby bisection 1

    midpoint 2

    11

    _

  • 7/25/2019 python3.odp

    135/458

    135

    '.&XX" 8 ".&

    ,.S _ 1 _ 1.S

    so change lowerbound

    midpoint 2_

    #@uare root of 1.Sby bisection 6

    #'.& = ".&* / ".&

  • 7/25/2019 python3.odp

    136/458

    136

    8id-point: ,.T

    #'.&= ".&* / ".&

    '.(

    '.(XX"

    "."(

    #@uare root of 1.Sby bisection 9

    '.(XX" + ".&

  • 7/25/2019 python3.odp

    137/458

    137

    '.( " ".&

    so change upperbound

    ,.S _ 1 _ ,.T

    #@uare root of 1.Sby bisection T

    #'.& = '.(* / ".&

  • 7/25/2019 python3.odp

    138/458

    138

    8id-point: ,.1T

    #'.& '.(* / ".&

    '."(

    '."(XX"

    '.(6"(

    #@uare root of 1.Sby bisection U

    '."(XX" 8 ".&

  • 7/25/2019 python3.odp

    139/458

    139

    so change lowerbound

    ,.1T _ 1 _ ,.T

    #@uare root of 1.Sby bisection V

    #'."(= '.(* / ".&

  • 7/25/2019 python3.odp

    140/458

    140

    8id-point: ,.6VT

    # *

    '.39(

    '.39(XX"

    '.:R&6"(

    #@uare root of 1.Sby bisection [

    '.39(XX" 8 ".&

  • 7/25/2019 python3.odp

    141/458

    141

    so change lowerbound

    ,.6VT _ 1 _ ,.T

    7xercise U

    One more iteration.

  • 7/25/2019 python3.odp

    142/458

    142

    ,.6VT _ 1 _ ,.T

    &ind the mid-point.#@uare it.

    *ompare the s@uare to 1.S.

    Do you chane thelower or upper bound

    1 minutes

    nderstanding before Programming

  • 7/25/2019 python3.odp

    143/458

    143

    And now using PythonC

    lower S &.&pper S " &

  • 7/25/2019 python3.odp

    144/458

    144

    pper S ".&

    Oiddle S #lower=pper*/"

    And now using Python 1

    OiddleXX" 8 ".&

  • 7/25/2019 python3.odp

    145/458

    145

    Ire

    lowerS Oiddle

    print#lower pper*

    ".&'.&

    And now using Python 6

  • 7/25/2019 python3.odp

    146/458

    146

    Oiddle S #lower=pper*/"

    print# OiddleXX"*Oiddle

    "."('.(

    And now using Python 9

    OiddleXX" 8 ".&

  • 7/25/2019 python3.odp

    147/458

    147

    ?alse

    pperS Oiddle

    print#lower pper*

    '.('.&

    And now using Python T

  • 7/25/2019 python3.odp

    148/458

    148

    Oiddle S #lower=pper*/"

    print# OiddleXX"*Oiddle

    '.(6"('."(

    And now using Python U

    OiddleXX" 8 ".&

  • 7/25/2019 python3.odp

    149/458

    149

    Ire

    lowerS Oiddle

    print#lower pper*

    '.('."(

    And now using Python V

  • 7/25/2019 python3.odp

    150/458

    150

    Oiddle S #lower=pper*/"

    print# OiddleXX"*Oiddle

    '.:R&6"('.39(

    And now using Python [

    OiddleXX" 8 ".&

  • 7/25/2019 python3.odp

    151/458

    151

    Ire

    lowerS Oiddle

    print#lower pper*

    '.('.39(

    5ooking at the Python codelower S &.&pper S ".&

  • 7/25/2019 python3.odp

    152/458

    152

    Oiddle S #lower=pper*/"

    print#Oiddle OiddleXX"*

    OiddleXX" 8 ".&

    lower S Oiddle pper S Oiddle

    print#lower pper*

    5ooking at the Python structureslower S &.&pper S ".&

    #et up

    5oop

  • 7/25/2019 python3.odp

    153/458

    153

    Oiddle S #lower=pper*/"

    print#Oiddle OiddleXX"*

    OiddleXX" 8 ".&

    lower S Oiddle pper S Oiddle

    print#lower pper*

    *hoice

    5ooping

    Before

  • 7/25/2019 python3.odp

    154/458

    154

    5oop test

    5oop body

    After

    #hould theloop run

    KagainL

    hat isrun eachloop

    5oop example: *ount from , to ,S

    nOer S 'Before

  • 7/25/2019 python3.odp

    155/458

    155

    nOer 8S '&

    print#nOer*nOer =S '

    print#None-*

    5oop test

    5oop body

    After

    5oop example: *ount from , to ,S

    nOer S 'nOer S '

  • 7/25/2019 python3.odp

    156/458

    156

    nOer 8S '&

    print#nOer*nOer =S '

    print#None-*

    while

    print#nOer*nOer =S '

    print#None-*

    )nOer 8S '&

    5oop test: *ount from , to ,S

    nOer S '

    3while4 keyword

    l t t

  • 7/25/2019 python3.odp

    157/458

    157

    while

    print#None-*

    )nOer 8S '&

    loop test

    colon

    print#nOer*nOer =S '

    5oop body: *ount from , to ,S

    nOer S '

  • 7/25/2019 python3.odp

    158/458

    158

    while

    print#None-*

    )nOer 8S '&

    loop body

    indentation

    print#nOer*nOer =S '

    nOer S '

    while nOer 8S '& )

    5oop example: *ount from , to ,S

    $

    '"

    python3 while1.py

  • 7/25/2019 python3.odp

    159/458

    159

    print#nOer* nOer =S '

    print#None-*

    while'.py

    34(

    69:R'&

    None-$

    Python?s use of indentation

    nOer S '

  • 7/25/2019 python3.odp

    160/458

    160

    while nOer 8S '& )

    p

    print#nOer*nOer =S '

    &our spaces? indentationindicate a 3block4 of code.

    )he block formsthe repeated lines.

    )he first unindented linemarks the end of the block.

    rint#None-*

    c.f.3legalese4

    ,,KaL

  • 7/25/2019 python3.odp

    161/458

    161

    ,KaL

    ,KbL,KbLKiL

    ,KbLKiiL

    ,KbLKiiiL

    ,KcL1

    6

    2ther languages

    #hell while ...

    do...

    do ... done #yntax

  • 7/25/2019 python3.odp

    162/458

    162

    *

    ...done

    while ...\......

    \ ... #yntax

    ...

    ...

    *larity

    *larity

    Progress

    while ... ) efore

    whiletest)ti

  • 7/25/2019 python3.odp

    163/458

    163

    action1

    action2

    action3

    afterwards

    test to keep looping

    code blocks

    indentation

    7xercise V

    &or each script:

    Predict what it will do

    while".py

    while3 py

  • 7/25/2019 python3.odp

    164/458

    164

    T minutes

    Predict what it will do.

    0un the script.

    ere you right

    while3.py

    while4.py

    while(.py

    )o kill a running script: *trl *;

    while6.py

    Back to our s@uare root example

    S.S 1.S

    1.S

    uncertainty

    ,.SY,S,T

    tolerance

  • 7/25/2019 python3.odp

    165/458

    165

    ,.T,.6VT

    ,.S 1.S

    ,.S

    ,.S ,.T

    S.T

    ,.1T ,.T

    S.1T

    S.,1T

    Y

    Y

    Y

    Y

    hat we get

    hat we want

    Meep looping while % toleranceuncertainty

  • 7/25/2019 python3.odp

    166/458

    166

    while nertainty + tolerane )

    Do stuff.

    #@uare root: the loop

    lower S &.&

    pper S ".&

    tolerane S '.&eV'(

    nertainty S pper V lower

    #et up

    5

  • 7/25/2019 python3.odp

    167/458

    167

    while nertainty + tolerane )

    Oiddle S #lower = pper*/"

    nertainty S pper V lower

    print#lower pper*

    5oop

    *hoice

    *hoosing

    OiddleXX" 8 ".&

    *hoice

  • 7/25/2019 python3.odp

    168/458

    168

    lower S Oiddle pper S Oiddle

    OiddleXX" 8 ".& Ire ?alseor

    Ire

    ?alse

    lower S Oiddle

    pper S Oiddle

    #imple example

    te!t S inpt#OerT *nOer S int#te!t*

    if nOer Y " SS &) print#Ben nOer*

    $

    OerTBen nOerIhat was fn

    python3 ithenel*e1.py

    "

  • 7/25/2019 python3.odp

    169/458

    169

    p # *else) print#Ddd nOer*

    print#Ihat was fn-*

    ifthenelse'.py

    Ihat was fn

    $

    OerTDdd nOerIhat was fn

    python3 ithenel*e1.py

    #

    if%then% else% + ,

    if )nOer Y " SS &

    ifkeyword

    )est

    *olon

  • 7/25/2019 python3.odp

    170/458

    170

    if

    else )

    print#Ben nOer*

    pper S Oiddle

    )nOer Y " & *olon

    print#Ihat was fn-*

    if%then% else% + 1

    if )nOer Y " SS &

  • 7/25/2019 python3.odp

    171/458

    171

    if

    else )

    print#Ben nOer*

    pper S Oiddle

    )nOer Y " &

    0un if test is "rue

    "ndentation

    print#Ihat was fn-*

    if%then% else% + 6

    if )nOer Y " SS &

  • 7/25/2019 python3.odp

    172/458

    172

    else )

    print#Ben nOer*

    pper S Oiddle

    else)keyword

    0un if test is False

    "ndentationprint#Ihat was fn-*

    if%then% else% + 9

    if )nOer Y " SS &

  • 7/25/2019 python3.odp

    173/458

    173

    else )

    print#Ben nOer*

    pper S Oiddle

    0un afterwardsregardlessof testprint#Ihat was fn-*

    2ur s@uare root example

    Oiddle S #lower = pper*/"

    if

    Before

    )OiddleXX" 8 ".&

  • 7/25/2019 python3.odp

    174/458

    174

    else )

    print#lower pper*

    lower S Oiddle

    pper S Oiddle

    After

    if% block

    Progress

    if ... ) efore

    iftest)action

    1

    else)

  • 7/25/2019 python3.odp

    175/458

    175

    1

    action2

    else)action

    3

    afterwards

    choice of two

    code blocks

    indentation

    7xercise [

    &or each script:

    Predict what it will do.

    ifthenelse".py

    ifthenelse3.py

  • 7/25/2019 python3.odp

    176/458

    176

    T minutes

    0un the script.

    ere you right

    ifthenelse4.py

    Back to our example

    lower S &.&

    pper S ".&

    tolerane S '.&eV'(

    nertainty S pper V lower

  • 7/25/2019 python3.odp

    177/458

    177

    while nertainty + tolerane )

    Oiddle S #lower = pper*/"

    nertainty S pper V lower

    print#lower pper*

    if OiddleXX" 8 ".& )

    else )

    pper S Oiddle

    lower S Oiddle

    Doublyindented

    ifstartsindented

    5e!els of indentation

    lower S &.&

    pper S ".&

    tolerane S '.&eV'(

    nertainty S pper V lower

  • 7/25/2019 python3.odp

    178/458

    178

    while nertainty + tolerane )

    Oiddle S #lower = pper*/"

    nertainty S pper V lower

    print#lower pper*

    if OiddleXX" 8 ".& )

    else )

    pper S Oiddle

    lower S Oiddle

    9 spaces

    [ spaces

    )rying it out

    tolerane S '.&eV'(lower S &.&

    pper S ".&nertainty S pper V lower

    while nertainty + tolerane )

    $

    '.& ".&'.& '.('."( '.(3

    python3 *qrt1.py

  • 7/25/2019 python3.odp

    179/458

    179

    while nertainty + tolerane ) Oiddle S #lower = pper*/"

    if OiddleXX" 8 ".&) lower S Oiddle else) pper S Oiddle

    print#lower pper*

    nertainty S pper V lower

    srt'.py

    '.39( '.('.39( '.439(

    '.4&6"( '.439('.4&6"( '.4"':9(

    ...

    '.4'4"'3... '.4'4"'3...

    #cript for the s@uare root of ".&

    lower S &.&

    tolerane S '.&eV'(

    nertainty S pper V lower

    hil t i t t l

    pper S .& 1.S

  • 7/25/2019 python3.odp

    180/458

    180

    while nertainty + tolerane )

    Oiddle S #lower = pper*/"

    nertainty S pper V lower

    print#lower pper*

    if OiddleXX" 8 .&)

    else )

    pper S Oiddle

    lower S Oiddle

    1.S

    "nput target

    te!t S inpt#OerT *nOerS float#te!t*

  • 7/25/2019 python3.odp

    181/458

    181

    if OiddleXX" 8 nu=er)

    %

    "nitial bounds

    lower S >pper S >

  • 7/25/2019 python3.odp

    182/458

    182

    # ,.S ,.S _ $#_ #

    ,.S # ,.S $# #

    if...then...else...

    "nitial bounds

    if nOer 8 '.& )lower S nOerpper S '.&else )

  • 7/25/2019 python3.odp

    183/458

    183

    else )lower S '.&pper S nOer

    eneric s@uare root scriptte!t S inpt#OerT*nOer S float#te!t*

    if nOer 8 '.&)

    lower S nOerpper S '.&else)lower S '.&

    ser input

    "nitiali`ation

  • 7/25/2019 python3.odp

    184/458

    184

    pper S nOer

    tolerane S '.&eV'(

    nertainty S pper V lower

    while nertainty + tolerane)Oiddle S #lower=pper*/".&if OiddleXX" 8 nOer)lower S Oiddleelse)

    pper S Oiddle

    nertainty S pper V lower

    print#lower pper*

    Processing

    2utput srt".py

    'egati!e numbers

    'eed to catch negati!e numbers

  • 7/25/2019 python3.odp

    185/458

    185

    e!it#*

    if nOer 8 &.&)print#Oer Ost e positie-*

    >uit immediately

    else is optional

    3*hained4 tests

    te!t S inpt#OerT*

    nOer S float#te!t*

    if nOer 8 &.&)print#Oer Ost e positie-*

    ser input

    "nput !alidation

  • 7/25/2019 python3.odp

    186/458

    186

    e!it#*

    if nOer 8 '.&)lower S nOerpper S '.&else)lower S '.&pper S nOer

    ...

    "nitiali`ation

    3*hained4 tests + syntactic sugar

    te!t S inpt#OerT*

    nOer S float#te!t*

    if nOer 8 &.&)print#Oer Ost e positie-*

    i #*

  • 7/25/2019 python3.odp

    187/458

    187

    elif

    e!it#*

    nOer 8 '.&)lower S nOerpper S '.&else)lower S '.&pper S nOer

    ...

    elif: 3else if4

    srt3.py

    ithout elif%

    te!t S inpt#OerT*

    nOer S float#te!t*

    if nOer 8 &.&)print#Oer is negatie.*l

  • 7/25/2019 python3.odp

    188/458

    188

    else)if nOer 8 '.&)print#Oer is etween ^ero and one.*else)if nOer 8 ".&)print#Oer is etween one and two.*else)if nOer 8 3.&)print#Oer is etween two and three.*else)print#Oer is three or Oore.*

    #tacked clauses get unwieldy

    ith elif%

    te!t S inpt#OerT*

    nOer S float#te!t*

    if nOer 8 &.&)print#Oer is negatie.*lif 8 ' &

  • 7/25/2019 python3.odp

    189/458

    189

    elif nOer 8 '.&)print#Oer is etween ^ero and one.*elif nOer 8 ".&)print#Oer is etween one and two.*elif nOer 8 3.&)print#Oer is etween two and three.*else)print#Oer is three or Oore.*

    Progress

    'ested structures

    if% )

    while % ) if % )

    *hained tests

  • 7/25/2019 python3.odp

    190/458

    190

    %elif% ) %elif% ) %else)

    %

    )esting inputs to scripts

    e!it#*

    7xercise \

    e!eriseR.py

    ,. 7dit the s@uare root script to catch negati!e numbers.

    Only attempt each part afteryou ha%e the pre%ious part wor&in!

  • 7/25/2019 python3.odp

    191/458

    191

    ,S minutes

    @ p g

    1. 7dit the s@uare root script to ask for the tolerance.

    6. 7dit the s@uare root script to catch negati!e tolerances.

    *omments

    e ha!e written our first real Python script

    hat did it do

  • 7/25/2019 python3.odp

    192/458

    192

    Whydid it do it

    'eed to annotate the script

    Python comment character

    )he 3hash4 character

    =a.k.a. 3pound4( 3number4( 3sharp4

  • 7/25/2019 python3.odp

    193/458

    193

    5ines starting with 3=4 are ignored

    Partial lines starting 3=4 are ignored

    sed for annotating scripts

    =

    Python commenting example

    Aript to allate sare roots y isetion #* Qo Nowling "&'". Liensed nder GPL 3.&te!t S inpt#OerT*nOer S float#te!t* eed a real nOer

    Iest nOer for alidity

  • 7/25/2019 python3.odp

    194/458

    194

    Iest nOer for alidity set initial onds if D`.if nOer 8 &.&)print#Oer Ost e nonVnegatie-*e!it#*elif nOer 8 '.&)lower S nOerpper S '.&else)lower S '.&pper S nOer

    2n a realnix system%

    -/sr/in/python3

    Aript to allate sare roots y isetion #* Qo Nowling "&'". Liensed nder GPL 3.&te!t S inpt#OerT*nOer S float#te!t* eed a real nOer

  • 7/25/2019 python3.odp

    195/458

    195

    nOer float#te!t* eed a real nOer

    8agic line for executable files

    $

    instead of

    u=+r.py

    $ python3 u=+r.py

    Progress

    *omments =

  • 7/25/2019 python3.odp

    196/458

    196

    =3=4 character

  • 7/25/2019 python3.odp

    197/458

    0ecap: Python types so far

    hole numbers

    &loating point numbers

    -,1V

    6.,9,T\1UT6T[\V\6

  • 7/25/2019 python3.odp

    198/458

    198

    )ext

    Booleans

    Ihe at sat on the Oat.

    )rue &alse

    *omplex numbers K,.S ; 1.SGL

    5ists

    [ hydrogen heliO lithiO erylliO

    oron ; thoriO protatiniO raniO]

  • 7/25/2019 python3.odp

    199/458

    199

    [ V3.'4'(R"6(3(:R9R3 V'.(9&9R63"69R4:R66

    &.& '.(9&9R63"69R4:R66 3.'4'(R"6(3(:R9R3]

    [ " 3 ( 9 '' '3 '9 'R]

    hat is a list

    A sequenceof !alues )he names of the elements

    hydroen' helium' lithium' beryllium' (' protactinium' uranium

  • 7/25/2019 python3.odp

    200/458

    200

    "ndi!idual !alue identifiedby position in the se@uence

    3helium4 is the name of thesecond element

    Ealues stored in order Atomic number order

    hat is a list

    A sequenceof !alues )he prime numbersless than sixty

    )' *' +' 7' 11' 1*' 17' 1,' )*' ),' *1' *7' -1' -*' -7' +*' +,

  • 7/25/2019 python3.odp

    201/458

    201

    "ndi!idual !alue identifiedby position in the se@uence

    less than sixty

    V is the fourth prime

    Ealues stored in order 'umerical order

    *reating a list in Python

    +++ prie* ? , 3, , #, 11, 13, 1#, 12@

    i

    A literal list

  • 7/25/2019 python3.odp

    202/458

    202

    +++ prie*

    [" 3 ( 9 '' '3 '9 'R]

    +++ type(prie*)

    8lass list+

    )he whole list

    A Python type

    ow Python presents lists

    #@uare brackets

    at the ends

  • 7/25/2019 python3.odp

    203/458

    203

    [ ]'R'9'3''9(3 "

    *ommas between items

    #@uare brackets

    priOes S [" 3 ( 9 '']5iteral list

  • 7/25/2019 python3.odp

    204/458

    204

    Python counts from ero

    96(43"'&3index4

  • 7/25/2019 python3.odp

    205/458

    205

    [ ]'R'9'3''9(3 "3!alue4

    5ooking things up in a list

    +++ prie* ? , 3, , #, 11, 13, 1#, 12@

    [ ]'R'9'3''9(3 "

    96(43"'&

  • 7/25/2019 python3.odp

    206/458

    206

    [ ]'R'9'3''9(3 "

    +++ prie*

    "

    +++

    '9

    @&?

    index

    prie* @7?

    s@uare brackets

    #@uare brackets

    priOes S [" 3 ( 9 ''] 5iteral list

    priOes[3] "ndex into list

  • 7/25/2019 python3.odp

    207/458

    207

    *ounting from the end

    +++ prie* ? , 3, , #, 11, 13, 1#, 12@

    [ ]'R'9'3''9(3 "

    96(43"'&

  • 7/25/2019 python3.odp

    208/458

    208

    [ ]'R'9'3''9(3 "

    +++

    'R

    prie* @1?

    getting at the last item

    V'V"V3V4V(V6V9V:

    "nside !iew of a listlist

    :

    priOesint 3

    int " primesjS

    primesj,

  • 7/25/2019 python3.odp

    209/458

    209

    int 'R

    %

    priOes

    int '9 primesjU

    primesjV

    5ength of a list

    priOes

    list

    :

    +++ len:

    (prie*)

    S len#*function:length of list

  • 7/25/2019 python3.odp

    210/458

    210

    priOes

    V8aximumindex is V

    *hanging a !alue in a list

    +++ d+t+ ?'+lph+', '=et+', '-++'@

    +++ d+t+?@

    gaOOa

    d ? @ ' '

    )he list

    "nitial !alue

  • 7/25/2019 python3.odp

    211/458

    211

    +++ d+t+?@ 'A'

    +++ d+t+?@

    G

    +++ d+t+

    [alpha eta G]

    *hange !alue

    *heck change

    *hanged list

    *hanging a !alue in a list + ,

    +++ d+t+ ?'+lph+', '=et+', '-++'@

    list

    3 str ( a l p h a

    0ight to left

  • 7/25/2019 python3.odp

    212/458

    212

    str 4 e t a

    str ( g a O O a

    *hanging a !alue in a list + 1

    +++ d+t+ ?'+lph+', '=et+', '-++'@

    data

    list

    3 str ( a l p h a

    0ight to left

  • 7/25/2019 python3.odp

    213/458

    213

    data

    str 4 e t a

    str ( g a O O a

    *hanging a !alue in a list + 6

    +++ d+t+?@ 'A'

    0ight to left

    data

    list

    3 str ( a l p h a

  • 7/25/2019 python3.odp

    214/458

    214

    data

    str 4 e t a

    str ( g a O O a

    str ' G 'ew !alue

    *hanging a !alue in a list + 9

    +++ d+t+?@ 'A'

    0ight to left

    data

    list

    3 str ( a l p h a

  • 7/25/2019 python3.odp

    215/458

    215

    data

    str 4 e t a

    str ( g a O O a

    str ' G'o longerreferenced

    *hanging a !alue in a list + T

    +++ d+t+?@ 'A'

    0ight to left

    data

    list

    3 str ( a l p h a

  • 7/25/2019 python3.odp

    216/458

    216

    data

    str 4 e t a

    str ' G

    0emo!ing an entry from a list + ,

    +++ del d+t+?1@

    data

    list

    3 str ( a l p h a data[&]

  • 7/25/2019 python3.odp

    217/458

    217

    data

    str 4 e t a

    str ( g a O O a

    data[']

    data["]

    0emo!ing an entry from a list + 1

    +++ del d+t+?1@

    data

    list

    " str ( a l p h a data[&]

  • 7/25/2019 python3.odp

    218/458

    218

    data

    str 4 e t a

    str ( g a O O a data[']

    'o longerreferenced

    0emo!ing an entry from a list + 6

    +++ del d+t+?1@

    data

    list

    " str ( a l p h a data[&]

  • 7/25/2019 python3.odp

    219/458

    219

    str ( g a O O a data[']

    0unning off the endlist

    :

    priOesint 3

    int "

  • 7/25/2019 python3.odp

    220/458

    220

    int 'R

    %

    int '9

    primesj[

    0unning off the end

    +++ len(prie*)

    :

    +++ prie*?#@

    'R

  • 7/25/2019 python3.odp

    221/458

    221

    'R

    +++ prie*?"@

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+

    nde!Brror) list inde! ot of range

    )ype of error Description of error

    0unning off the end

    +++ prie*?"@ 3

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+nde!Brror) list assignOent inde! ot of range

    # t #i il d i ti f

  • 7/25/2019 python3.odp

    222/458

    222

    #ame typeof error

    #imilar description of errorbut with 3assignment4

    Progress

    5ists

    index

    *ount from `ero

    [" 3 ( 9 '' '3 '9 'R]

    priOes[4]

    priOes[&]

  • 7/25/2019 python3.odp

    223/458

    223

    5ength

    2!er-running

    len#priOes*

    priOes[:]

    Deletion del priOes[6]

    7xercise ,,

    )rack what the !alue of nOersis at each stage of thisse@uence of instructions.

    nu=er* ?, #, 11, 13, 1#, 12, 2, 31@+++

    nu=er*?1@ 3+++

    ,

    1

  • 7/25/2019 python3.odp

    224/458

    224

    T minutes

    ? @

    del nu=er*?3@+++

    nu=er*?3@ 3#+++

    nu=er*?0@ nu=er*?@+++

    6

    9

    T

    ow can we add to a list

    list

    :

    %

    int "

    list

    R

    %

    int "

    #ame list

    'ew length

  • 7/25/2019 python3.odp

    225/458

    225

    int 'R

    int '9

    int 'R

    int '9

    int "37xtra item

    Appending to a list

    +++ prie*

    [" 3 ( 9 '' '3 '9 'R]

    +++ prie* (3)+ppend

    A function built into a list

  • 7/25/2019 python3.odp

    226/458

    226

    +++ prie*

    +++ prie*

    [" 3 ( 9 '' '3 '9 'R

    (3)+ppend.

    )he list is now updated

    ]"3

    priOes.append#*

    +++ prie* (3)+ppend

    )he list

    A connecting dot

    append#*

  • 7/25/2019 python3.odp

    227/458

    227

    +++ prie* (3)+ppend. append#*

    )he !alue to append

    All lists ha!e this

    function built in.

    38ethods4

    (arguments)object function.

    Beha!es Gustlike a function

  • 7/25/2019 python3.odp

    228/458

    228

    a function that has

    special access tothe obGect?s data.

    sing the append#*method

    +++ print(prie*)

    [" 3 ( 9 '' '3 '9 'R]

    +++ prie* (3)+ppend.

    +++ prie* (2)+ppend

    )he function doesn?treturn any !alue.

  • 7/25/2019 python3.odp

    229/458

    229

    +++ prie* (2)+ppend.

    +++ prie* (31)+ppend.

    +++ prie* (3#)+ppend.

    +++ print(prie*)

    [" 3 ( 9 '' '3 '9 'R "3 "R 3' 39]

    "t modifiesthe list itself.

    2ther methods on lists: reerse#*

    +++ nu=er* ?0, #, , 1@

    +++ nu=er*.reBer*e()

    +++ print(nu=er*)

    )he function doesn?treturn any !alue.

  • 7/25/2019 python3.odp

    230/458

    230

    +++ print(nu=er*)

    [' ( 9 4]"t modifiesthe list itself.

    2ther methods on lists: sort#*

    +++ nu=er* ?0, #, , 1@

    +++ nu=er*.*ort()

    +++ print(nu=er*)

    )he function does notreturn the sorted list.

  • 7/25/2019 python3.odp

    231/458

    231

    print(nu=er*)

    [' 4 ( 9]

    'umerical order.

    "t sorts thelist itself.

    2ther methods on lists: sort#*

    +++ -reeC ?'+lph+', '=et+', '-++', 'delt+'@

    +++ -reeC.*ort()

    +++ print(-reeC)

  • 7/25/2019 python3.odp

    232/458

    232

    p (- )

    [alpha eta delta gaOOa]

    Alphabetical order

    of the words.

    2ther methods on lists: insert#*

    +++ -reeC '-++',?'+lph+',

    S , 1

    +++ -reeC.in*ert(

    'delt+'@

    here to insert hat to insert

    '=et+'1, )

  • 7/25/2019 python3.odp

    233/458

    233

    e e to se t at to se t

    +++ -reeC

    [alpha gaOOa delta]eta

    ,Displaced

    S

    2ther methods on lists: reOoe#*

    +++ nu=er* ?#, 0,

    +++ nu=er*.reoBe

    #, , , 0@",

    (")

    alueto remo!e

  • 7/25/2019 python3.odp

    234/458

    234

    +++ print(nu=er*)

    [9 4 9 " ( 4]

    c.f. del nOers["] !ndexto remo!e

    2ther methods on lists: reOoe#*

    +++

    +++ nu=er*.reoBe(0)

    print(nu=er*)

    [9 9 " (4 4]

    )here are two instances of 9.

  • 7/25/2019 python3.odp

    235/458

    235

    +++ print(nu=er*)

    [9 9 " ( 4]

    2nly the first instance is remo!ed

    hat methods are there

    +++ help(nu=er*)

    ,elp on list oUet)

    lass list#oUet*... append#...*

  • 7/25/2019 python3.odp

    236/458

    236

    L.append#oUet* VV append oUet to end...

    Pagination:

    B

    next page

    back one page

    > @uit

    elp on a single method

    +++ help(nu=er*.+ppend)

    ,elp on iltVin fntion append)

    append#...* L.append#oUet* VV append oUet to end

  • 7/25/2019 python3.odp

    237/458

    237

    #orting a list redux

    +++ -reeC ?'+lph+', '=et+', '-++', 'delt+'@

    +++ -reeC.*ort() 0ecall: greek.sort#*sorts the list 3in place4.

  • 7/25/2019 python3.odp

    238/458

    238

    +++ print(-reeC)

    [alpha eta delta gaOOa]

    #orting a list redux: 3sortedKL4

    +++ -reeC ?'+lph+', '=et+', '-++', 'delt+'@

    +++ print(*orted(-reeC)) sorted#*functionreturns a sorted list%

    [alpha eta delta gaOOa]

  • 7/25/2019 python3.odp

    239/458

    239

    +++ print(-reeC)

    [alpha eta gaOOa delta]

    %and lea!es thelist alone

    Adding to a list redux: 3;4

    +++ prie*

    [" 3 ( 9 '' '3 '9 'R]

    *oncatenationoperator

    5ist to add

  • 7/25/2019 python3.odp

    240/458

    240

    +++ prie*

    [" 3 ( 9 '' '3 '9 'R

    ?3, 2, 31@

    "3 "R 3']

    *oncatenation

    +++ newli*t

    +++

    prie* ?3, 2, 31@

    prie* prie* ?3, 2, 31@

    *reate a new list

    pdate the list

  • 7/25/2019 python3.odp

    241/458

    241

    +++ prie* ?3, 2, 31@

    Augmented assignment

    *reating lists from text + ,

    +++ li*t('Hello')

    [, e l l o] list

    (

    str ' ,

    str ' e

  • 7/25/2019 python3.odp

    242/458

    242

    str ( , e l l o str ' l

    str ' l

    str ' o

    *reating lists from text + 1

    +++ 'Hello, world!'

    [,ello world-]

    , e l l o w o r l d -'3str

    .*plit()

    Built in method

    #plits on spaces

  • 7/25/2019 python3.odp

    243/458

    243

    list

    " str 6 , e l l o

    str 6 w o r l d -

    Progress38ethods4

    append#iteO*

    reerse#*

    sort#*

    insert#inde!iteO*

    reOoe#iteO*

    object.method#arguments*

    h l # bj *

  • 7/25/2019 python3.odp

    244/458

    244

    *oncatenation=

    =S

    ['"3] = [4(6]

    priOes =S ["R 3']

    #orting list.sort#*sorted#list*

    elp help#object*help#object.method*

    7xercise ,1

  • 7/25/2019 python3.odp

    245/458

    245

    T minutes

    "s an item in a list + ,

    +++ odd* ?3, , #, 2@ Does not include 1

    +++ odd*.reoBe()

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+

    W l B

    ard error

    li t # * t i li t

    )ry to remo!e 1

  • 7/25/2019 python3.odp

    246/458

    246

    WaleBrror) list.reOoe#!*) ! not in list

    x must be in thelist before it can

    be remo!ed

    "s an item in a list + 1+++ odd* ?3, , #, 2@

    +++ in odd*

    ?alse

    +++ 3 i dd

  • 7/25/2019 python3.odp

    247/458

    247

    +++ 3 in odd*

    Ire

    +++ not in odd*

    Ire

    Precedence

    !44y !4y!5y!6y !y!y!!

    !y !:y!:y!!y !9y!9y

    &irst

  • 7/25/2019 python3.odp

    248/458

    248

    not! ! or y! +nd y

    5ast

    ! not iny ! in y

    )he list now contains

    e!ery operator wemeet in this course.

    #afe remo!al

    if nOer in nOers )

    nOers.reOoe#nOer*

    hat?s thedifference

  • 7/25/2019 python3.odp

    249/458

    249

    while nOer in nOers )

    nOers.reOoe#nOer*

    orking through a list + ,

    e.g. Printing each element on a line

    [Ihe at sat on the Oat.]

    Ihe

  • 7/25/2019 python3.odp

    250/458

    250

    Iheatsatonthe

    Oat.

    orking through a list + 1

    e.g. Adding the elements of a list

    [4( 96 V"3 R& '(]

    "&3

  • 7/25/2019 python3.odp

    251/458

    251

    "&3

    hat is the sum of an empty list []

    orking through a list + 6

    e.g. #@uaring e!ery number in a list

    [4 9 V" R ']

    ['6 4R 4 :' ']

  • 7/25/2019 python3.odp

    252/458

    252

    ['6 4R 4 :' ']

    )he 3for loop4 + ,

    words [Ihe at sat on the Oat.]S

    for )wordsinword

    name of list list

    A new Python

  • 7/25/2019 python3.odp

    253/458

    253

    for

    )wordsinword

    print#word*

    A new Pythonlooping construct

    print: hat we want

    to do with the list items.

    )he 3for loop4 + 1

    words [Ihe at sat on the Oat.]S

    for )wordsinword

    keywords

  • 7/25/2019 python3.odp

    254/458

    254

    for

    )wordsinword

    print#word*

    colon followed byan indented block

    )he 3for loop4 + 6

    words [Ihe at sat on the Oat.]S

    for )wordsinword

    Defining the loop %ariable

  • 7/25/2019 python3.odp

    255/458

    255

    word*

    for )wordsinword

    print#

    sing the loop !ariable

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    256/458

    256

    str " o n

    str 3 t h e

    str 4 O a t .

    words

    &irst loop

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    257/458

    257

    str " o n

    str 3 t h e

    str 4 O a t .

    words

    #econd loop

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    258/458

    258

    str " o n

    str 3 t h e

    str 4 O a t .

    words

    )hird loop

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    259/458

    259

    str o

    str 3 t h e

    str 4 O a t .

    words

    &ourth loop

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    260/458

    260

    str

    str 3 t h e

    str 4 O a t .

    words

    &ifth loop

    0unning the 3for loop4

    list

    6

    str 3 I h e

    str 3 a t

    str 3 s a t

    str " o n

    word

    for )wordsinwordword*print#

  • 7/25/2019 python3.odp

    261/458

    261

    str 3 t h e

    str 4 O a t .

    words

    &inal loop

    )he 3for loop4 for printing

    words [Ihe at sat on the Oat.]S

    for )wordsinword

  • 7/25/2019 python3.odp

    262/458

    262

    word*print#

    for'.py

    )he 3for loop4 for adding

    nOers S [4( 96 V"3 R& '(]

    for )in

    total S &

    nOer nOers

    #et up before the loop

  • 7/25/2019 python3.odp

    263/458

    263

    total =S

    print#total*

    nOer Processing in the loop

    0esults after the loop

    for".py

    )he 3for loop4 for creating a new list

    nOers S [4 9 V" R ']

    for )in

    sares S [ ]

    nOer nOers

    #et up before the loop

  • 7/25/2019 python3.odp

    264/458

    264

    sares.append#

    print#sares*

    Processing in the loop

    0esults after the loop

    nOerXX"*

    for3.py

    )he loop !ariable persistsCnOers S [4 9 V" R ']

    for )in

    sares.append#

    sares S [ ]

    nOer nOers

    print#

    nOerXX"*

    *nOer

    5oop !ariable onlymeant for use in loopC

    But it persistsC

  • 7/25/2019 python3.odp

    265/458

    265

    print# *nOer But it persistsC

    3for loop hygeine4nOers S [4 9 V" R ']

    for )in

    sares.append#

    sares S [ ]

    nOer nOers

    del

    nOerXX"*

    nOer Delete it after use

  • 7/25/2019 python3.odp

    266/458

    266

    del nOer Delete it after use

    Progress

    )esting items in lists

    for loops

    3 in['"34]

    total S &ornOer in['"34]D

    total =S nOerdel nOer

    Ire

  • 7/25/2019 python3.odp

    267/458

    267

    del nOer

    loop !ariables for nu=erin ['"34])

    total =S nu=erdelnu=er

    7xercise ,6

    hat does this print

    nOers S [& ' " 3 4 (]

    total S &

    total_so_far S []

  • 7/25/2019 python3.odp

    268/458

    268

    T minutes

    for nOer in nOers) total =S nOer total_so_far.append#total*

    print#total_so_far*

    3#ort-of-lists4

    Python 3magic4:

    )reat it like a list and it will

    beha!e like a usefullist

  • 7/25/2019 python3.odp

    269/458

    269

    hat can 3it4 be

    #trings as lists0ecall:

    list#,ello* [, e l l o]

    for letter in ,e print#letter* ),ello

  • 7/25/2019 python3.odp

    270/458

    270

    llo

    p # *

    ets turned

    into a list.for4.py

    *reating lists of numbersBuilt in to Python:

    range#startlimit*

    for nOer in print#nOer* )range#3:* 34

  • 7/25/2019 python3.odp

    271/458

    271

    p # *(69

    [ not included

    ranges of numbers'ot actually lists: +++

    range#&(*

    r+n-e(&,)

    But close enough: +++

    [& ' " 3 4]

    li*t(r+n-e(&,))

  • 7/25/2019 python3.odp

    272/458

    272

    [ ]

    )reat it like a list and

    it will beha!e like a list

    hy not Gust a list8ost common use: for nOer in

    ;range#& '&&&&*)

    "nefficient to make ahuge list Gust for this

    3iterator4 : anything that can be treated like a list

  • 7/25/2019 python3.odp

    273/458

    273

    list#iterator* 7xplicit list

    0anges of numbers again

    range#'&* [& ' " 3 4 ( 6 9 : R]

    range#3 '&* [3 4 ( 6 9 : R]

    range#3 '& "* [3 ( 9 R]

    !ia list#*

    #tart at S

    7!ery nth number

  • 7/25/2019 python3.odp

    274/458

    274

    range#3 '& "* [3 ( 9 R] 7!ery n number

    range#'& 3 V"* ['& : 6 4] 'egati!e steps

    "ndices of lists+++ prie* ? , 3, , #, 11, 13, 1#, 12@

    +++ len(prie*)

    +++ li*t(r+n-e(

    :

    [& ' " 3 4 ( 6 9]

    "))

    !alid indices

  • 7/25/2019 python3.odp

    275/458

    275[ ]'R'9'3''9(3 "

    96(43"'&

    Direct !alue or !ia the indexpriOes S [" 3 ( 9 '' '3 '9 'R]

    for priOe in priOes) print#priOe*

    #impler

  • 7/25/2019 python3.odp

    276/458

    276

    for inde! in range#len#priOes**) print#priOes[inde!]*

    7@ui!alent

    orking with two lists: 3dot product4

    list' S [ &.4]&.&&.3

    list" S [ &.6]&.(&."

    ZZZ

    &."4&.&&.&6 = = &.3

    b

  • 7/25/2019 python3.odp

    277/458

    277

    orking with two lists: indices

    list' S [&.3 &.& &.4]list" S [&." &.( &.6]

    for inde! in

    sO S &.&

    S , 1

    indices

    )range#len#list'**

    li t'[i d ]Xli t"[i d ]

  • 7/25/2019 python3.odp

    278/458

    278

    print#sO*

    sO =S list'[inde!]Xlist"[inde!]

    Dealing with!alues from

    both lists atthe same time.

    iter

    4

    "

    A little more about iterators + ,

    str ( a l p h a

    str 4 e t a

    +++ -reeC ?'+lph+', '=et+', '-++', 'delt+'@

    +++ -reeCEi iter(-reeC)

    +++ next(-reeCEi)

    alpha 2ffset

  • 7/25/2019 python3.odp

    279/458

    279

    str ( g a O O a

    str ( d e l t a

    +++ next(-reeCEi)

    eta

    iter

    4

    A little more about iterators + 1

    str ( a l p h a

    str 4 e t a

    str ( g a O O a

    str ( d e l t a

    +++ next(-reeCEi)

    gaOOa

    +++ next(-reeCEi)

    delta

  • 7/25/2019 python3.odp

    280/458

    280

    str ( d e l t a

    +++ next(-reeCEi)

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+Atopteration

    Progress

    'on-lists as lists

    3"terators4

    range#* range#liOit*range#startliOit*

    range#startliOitstep*

    range#39* [34(6]

    for letter in ,ello) ...

    greek_i S iter#greek*

    ne!t#greek i*

  • 7/25/2019 python3.odp

    281/458

    281

    "ndices of lists

    Parallel lists

    for inde! in range#len#things**)

    ne!t#greek_i*

    7xercise ,9

    list' S [ &.4]&.&&.3

    list" S [ &.6]&.(&."

    V&."V&.(&.'

    *omplete e!erise'4.py

    Difference

    #@uare

  • 7/25/2019 python3.odp

    282/458

    282

    T minutes

    &.&4&."(&.&' &.3==

    #@uare

    Add

    5ist 3slices4

    prie* ?, 3, , #, 11, 13, 1#, 12, 3, 2@

    prie*

    [" 3 ( 9 '' '3 '9 'R "3 "R]

    prie*?3@9

    )he list

    An item

  • 7/25/2019 python3.odp

    283/458

    283

    prie*?3D2@

    [9 '' '3 '9 'R "3] "artof the list

    #lices + ,

    priOes S [" 3 ( 9 '' '3 '9 'R "R 3']

    6 \

    "3

    priOes[ ]R)3

    to

    fromp to but notincluding%

  • 7/25/2019 python3.odp

    284/458

    284

    [9priOes[3)R]

    "tem \ notincluded

    '' '3 '9 'R "3]

    #lices + 1

    priOes 9 '' '3 '9 'R "R 3']"3

    priOes[ ]R)3 [9 '' '3 '9 'R "3]

    [" 3 (

    priOes[ ]R) [" 3 ( 9 '' '3 '9 'R "3]

    priOes[ ])3 [9 '' '3 '9 'R "3 "R 3']

  • 7/25/2019 python3.odp

    285/458

    285

    priOes[ ])3 [9 '' '3 '9 'R "3 "R 3']

    priOes[ ]) [" 3 ( 9 '' '3 '9 'R "3 "R 3']

    #lices + 6

    priOes 9 '' '3 '9 'R "R 3']"3

    priOes[ ]R)3 [9 '' '3 '9 'R "3]

    [" 3 (

    priOes[ )R)3 [9 '3 'R ]]"

    priOes[ )R)3 ]3 [9 '9 ]

  • 7/25/2019 python3.odp

    286/458

    286

    priOes[ )R)3 ]3 [9 '9 ]

    list

    3letters

    *opies and slices + ,

    letter* ?'+','=',''@

    str ' a

    +lph+=et letter*

  • 7/25/2019 python3.odp

    287/458

    287

    alphaet

    str '

    str '

    list

    3letters

    *opies and slices + 1

    letter*?&@ 'F'+++

    str ' J

    print(+lph+=et)+++

    [J ]

  • 7/25/2019 python3.odp

    288/458

    288

    alphaet

    str '

    str '

    letters alphaet

    list

    3

    *opies and slices + 6

    letter* ?'+','=',''@+++

    str ' a

    +lph+=et letter*?D@+++

    list

    3

    #lices arecopies.

  • 7/25/2019 python3.odp

    289/458

    289

    str '

    str '

    *opies and slices + 9

    letter*?&@ 'F'+++

    print(+lph+=et)+++

    #lices arecopies.

    [a ]

    letters

    alphaet

    list

    3str ' a

    list

    3str ' F

  • 7/25/2019 python3.odp

    290/458

    290

    str '

    str '

    Progress

    #lices

    iteOs[froO)to]

    iteOs[)to]

    iteOs[froO)to)stride]

    iteOs[)to)stride]

    7nd-limit excluded

    #lices are copies

  • 7/25/2019 python3.odp

    291/458

    291

    [ ]

    iteOs[froO)]

    iteOs[)]

    [ ]

    iteOs[froO))stride]

    iteOs[))stride]

    7xercise ,T

    Predict what this Python will do.)hen run it.ere you right

    e!erise'(.py

    foo S [4 6 " 9 3 ' R 4 " 9 4 6 & "]

    ar S foo[3)'")3]

    ar["] =S foo[4]

  • 7/25/2019 python3.odp

    292/458

    292

    6 minutes

    foo[&] S ar[']

    print#ar*

    list

    (

    Di!ersion: 5ists and strings

    )ext: 3a strinof characters4

    list#*

    str ' ,

    str ' e

    str ' l

    str ' l

    str ( , e l l o

  • 7/25/2019 python3.odp

    293/458

    293

    str ' o

    "ndexing into strings

    'Hello, world!'?&@+++

    ,

    'Hello, world!'?D0@+++

    ,ell

    #imple indexing

    #licing

  • 7/25/2019 python3.odp

    294/458

    294

    #trings are immutable

    'Hello, world!'?&@ ';'+++

    Iraeak #Oost reent all last*) ?ile >8stdin+> line ' in 8Oodle+IypeBrror) str oUet does not spport

    iteO assignOent

  • 7/25/2019 python3.odp

    295/458

    295

    &iles

    .t!t

    .dat

    .s

    "nput 2utput

  • 7/25/2019 python3.odp

    296/458

    296

    .s

    0eading riting

    0eading a text file

    &ile name

    &ile obGect

    il

    treasre.t!t

    ook

    IHBJAFHB ALJN

    string

    file

    t i

    3opening4 the file

    reading from the file

  • 7/25/2019 python3.odp

    297/458

    297

    &ile contents IHBJAFHB ALJN string

    &inished with the file

    3closing4 the file

    2pening a text file

    +++ =ooC )'r','tre+*ure.txt'(open

    0ead-only jtext

    &ile name

    Python function

    Python file obGect

    3mode4

  • 7/25/2019 python3.odp

    298/458

    298ook *treasre.t!t#openS

    0ead-only isthe default

    0eading from a file obGect

    +++ line1 =ooC

    &ile obGect

    &irst line of file

    +++ line1 "ncludes the

    next( )

    3next line( please4

  • 7/25/2019 python3.odp

    299/458

    299

    +++ line1

    7nIHBJAFHB ALJN

    "ncludes the3end of line4

    &ile obGect are iterable

    +++ line next(=ooC)

    #econd line of file

    +++ line

    7n

    +++ line3 next(=ooC)

    A blank line

  • 7/25/2019 python3.odp

    300/458

    300

    +++ line3

    PJHI DB7n

    )hird line of file

    *losing the file

    +++ .lo*e()=ooC

    8ethod built in to file obGect

    &rees the file for otherprograms to write to it.

  • 7/25/2019 python3.odp

    301/458

    301

    )he file obGect + ,

    +++ =ooC

    8_io.Ie!tDKrapper

    enodingSFI?V:+naOeStreasre.t!t

    )ext "nput/2utput

    &ile name

    *haracter encoding:how to representletters as numbers

  • 7/25/2019 python3.odp

    302/458

    302

    letters as numbers.

    )he file obGect + 1

    file "R treasre.t!t FI?V:

    IHBJAFHB ALJN

    PJHI DB

    Ihe Dld Qaneer

    3offset4: how far into

    the file we ha!e read

    &ile name

    )ext encoding

  • 7/25/2019 python3.odp

    303/458

    303

    Pointer to the fileon the file system

    0eading through a file

    )reat it like a list andit will beha!e like a list

    list#file_object* 5ist of lines in the file

    +++ =ooC open('tre+*ure.txt', 'r')

    +++ line* li*t(=ooC)

  • 7/25/2019 python3.odp

    304/458

    304

    +++ line* li*t(=ooC)

    +++ print(line*)

    0eading a file mo!es the offset

    C+++ =ooC open('tre+*ure.txt', 'r')

    +++ line*E+ li*t(=ooC)

    +++ print(line*E+)

    +++ line*E= li*t(=ooC)

    uge output%

  • 7/25/2019 python3.odp

    305/458

    305

    +++ print(line*E=)

    [] 7mpty list

    0eading a file mo!es the offset

    +++ =ooC

    +++ line*E+

    +++ print(line*E+)

    +++

    %

    &ile obGect starts with offset at start.

    open('tre+*ure.txt', 'r')

    2peration reads entire file from offset.

    li*t(=ooC)

    line*E= li*t(=ooC)

    2ffset changed to endof file.

    i d i fil f ff

  • 7/25/2019 python3.odp

    306/458

    306

    +++ print(line*E=)

    []

    2peration reads entire file from offset.

    #o thereQs nothing left to read.

    0esetting the offset

    +++ =ooC

    +++ line*E+

    +++ print(line*E+)

    +++

    %

    open('tre+*ure.txt', 'r')

    li*t(=ooC)

    =ooC.*eeC(&) #et the offset explicitly

  • 7/25/2019 python3.odp

    307/458

    307

    +++ line*E= li*t(=ooC)

    +++ print(line*E=)

    )ypical way to process a file

    ook S open#treasre.t!t r*

    for line in ook )

    %

    )reat it like a list%

  • 7/25/2019 python3.odp

    308/458

    308

    7xample: lines in a file

    ook S open#treasre.t!t r*

    n_lines S &

    for line in ook )

    n_lines =S '

    5ine count

    0ead each line of the file

    "ncrement the count

  • 7/25/2019 python3.odp

    309/458

    309

    print#n_lines* Print out the count

    ook.lose#*

    7xample: characters in a file

    ook S open#treasre.t!t r*

    n_hars S &

    for line in ook )

    n_hars len#line*

    'umber of characters on the line

    "ncrease the count by that many

    =S

  • 7/25/2019 python3.odp

    310/458

    310

    print#n_hars*y y

    ook.lose#*

    Progress

    2pening file to read

    0eading file

    *losing file

    &ile offset

    ook S open#filenaOe r*

    ook.lose#*

    ook.seek#&*

    for line in ook) ...

  • 7/25/2019 python3.odp

    311/458

    311

    7xercise ,U

    *omplete a script to countlines( words and characters

    of a file.

    e!erise'6.py

  • 7/25/2019 python3.odp

    312/458

    312T minutes

    riting files

    &ile name

    Data to write

    &ile obGect

    treasre.t!t

    ook

    IHBJAFHB ALJN

    string

    file

    string

    3opening4 the file

    writing to the file

  • 7/25/2019 python3.odp

    313/458

    313

    &inished with the file

    3closing4 the file

    2pening a text file for writing

    +++ output )'w','output.txt'(open

    2pen for

    writing jtext

    )hi ill t t

  • 7/25/2019 python3.odp

    314/458

    314C

    )his will truncatean existing file

    2pening a text file for appending

    +++ output )'+','output.txt'(open

    2pen for

    appending jtext

  • 7/25/2019 python3.odp

    315/458

    315

    riting to a file obGect + ,

    +++ .writeoutput

    8ethod built into file obGect

    &ile obGect

    (line1)

    Data being written6

    'umber ofcharactersactually written

  • 7/25/2019 python3.odp

    316/458

    316

    actually written

    +++ len(line1)

    6

    riting to a file obGect + 1

    +++ .writeoutput ('+lph+ )ypical use: whole line.

    "ncludes 3end of line4

    %n')

    +++ .writeoutput ('=e')

    +++ .writeoutput ('t+%n')

    Doesn?t ha!eto be whole lines

    +++ writeoutput ('-++%ndelt+%n')

    6

    "

    3

  • 7/25/2019 python3.odp

    317/458

    317

    +++ .writeoutput ('-++%ndelt+%n')

    *an be multiple lines

    '"

    *losing the file obGect

    +++ .lo*e()output Eital for written files

  • 7/25/2019 python3.odp

    318/458

    318

    "mportance of closing

    Data 3flushed4 to disc on closure.

    write 3flush4

    C

  • 7/25/2019 python3.odp

    319/458

    319Python script &ile obGect &ile system

    "mportance of closingpromptly

    C&iles locked for other accessopen jQwQ open jQrQ

  • 7/25/2019 python3.odp

    320/458

    320

    K8ore a problem for indows than nixL

    riting non-text !alues

    +++ output.write('/oo!%n') riting text KstrL

    (

    +++ output.write(0) riting non-text KintL

    Iraeak #Oost reent all last*)

    ?ile >8stdin+> line ' in 8Oodle+IypeBrror) Ost e str not int

    write#*only accepts text

  • 7/25/2019 python3.odp

    321/458

    321

    riting non-text !alues

    +++ output.write( *on!ert to text: str#*

    "

    +++ output.write('%n') 7xplicit end-of-line

    '

    *tr(0))

  • 7/25/2019 python3.odp

    322/458

    322

    )ext formatting Klater in the courseL

    pro!ides a more elegant solution.

    Progress

    2pening files for writing

    7xplicit ends of lines

    ook S open#filenaOe w*

    ook.write#7n*

    riting data ook.write#str#data**

    riting text ook.write#te!t*

  • 7/25/2019 python3.odp

    323/458

    323*losing the file is important ook.lose#*

    7xercise ,V

    )he script e!erise'9.pyprintsa series of numbers ending in ,.

    *hange the script to write to a file calledotpt.t!tinstead of printing to the console.

  • 7/25/2019 python3.odp

    324/458

    324T minutes

    &unctions

    y = f(

    x)

  • 7/25/2019 python3.odp

    325/458

    325

    &unctions we ha!e met

    print#line*

    open#filename mode*

    range#from to, stride*

    float#thing*

    int#thing*

    iter#list*

    str#thing*

    len#thing*

    type#thing*

    inpt#prompt*

    ool#thing*

    ord#char*

    hr#number*

    list#thing*

  • 7/25/2019 python3.odp

    326/458

    326

    # g*

    'ot that manyC 3)he Python ay4:"f it is appropriate to an obGect(make it a method of that obGect.

    # *

    Whywrite our own functions

    % read

    % test

    % fix

    % impro!e

    % add to

    % write

    7asier to %

    3#tructuredprogramming4

  • 7/25/2019 python3.odp

    327/458

    327

    programming

    % de!elop

    Defining a function

    (y1, y2, y3) (x1, x2, x3, x4, x5)= f

    Identifythe inputs

    Identifythe processing

    Identifythe outputs

  • 7/25/2019 python3.odp

    328/458

    328

    A function to define: total#*

    #um a list

    j,( 1( 6

    jV( -9( ,( U( S

    j

    U

    ,S

    S 37dge case4

  • 7/25/2019 python3.odp

    329/458

    329

    j

    Defining a Python function + ,

    def )# ; *total colon

    inputs

    name of function

    define a function called %

  • 7/25/2019 python3.odp

    330/458

    330

    Defining a Python function + 1

    def total# *)nOers

    name for the input

    )his name isinternaltothe function.

  • 7/25/2019 python3.odp

    331/458

    331

    Defining a Python function + 6

    def total#nOers*) *olon followed by indentation

  • 7/25/2019 python3.odp

    332/458

    332

    Defining a Python function + 9

    def total#nOers*)

    sO_so_far S &

    for nOer in nOers) sO_so_far =S nOer 3Body4 of function

  • 7/25/2019 python3.odp

    333/458

    333

    Defining a Python function + 9

    def total# *)nOers

    sO_so_far

    forsO_so_far =S nOer

    S &

    in nOers)nOer

    )hese !ariables exist onlywithin the function?s body.

  • 7/25/2019 python3.odp

    334/458

    334

    Defining a Python function + T

    def total#nOers*)

    sO_so_far S &

    for nOer in nOers) sO_so_far =S nOer

    retrn sO_so_far)his !alueis returned

  • 7/25/2019 python3.odp

    335/458

    335returnthis !alue

    Defining a Python function + U

    def total#nOers*)

    sO_so_far S &

    for nOer in nOers) sO_so_far =S nOer

    retrn sO_so_far

    And that$s it%

  • 7/25/2019 python3.odp

    336/458

    336

    nindented

    after this

    Defining a Python function + V

    And that$s it%

    All internal names cleaned up 'o need for del

    All internal names internal 'o need to a!oid reusing names

  • 7/25/2019 python3.odp

    337/458

    337

    sing a Python function + ,def total#nOers*)

    sO_so_far S &

    for nOer in nOers) sO_so_far =S nOer

    retrn sO_so_far

    print#total#[' " 3]**

    )he list wewant to add up

  • 7/25/2019 python3.odp

    338/458

    338

    want to add up

    sing a Python function + 1def total#nOers*)

    sO_so_far S &

    for nOer in nOers) sO_so_far =S nOer

    retrn sO_so_far

    print#total#[' " 3]**

    )he function weha!e Gust written

  • 7/25/2019 python3.odp

    339/458

    339

    G

    sing a Python function + 6def total#nOers*)

    sO_so_far S &

    for nOer in nOers)

    sO_so_far =S nOer

    retrn sO_so_far

    print#total#[' " 3]**

    Printing outthe answer

  • 7/25/2019 python3.odp

    340/458

    340

    sing a Python function + 9def total#nOers*)

    sO_so_far S &

    for nOer in nOers)

    sO_so_far =S nOer

    retrn sO_so_far

    print#total#[' " 3]**

    $ python3 tot+l1.py

    6

    nb: nix prompt

  • 7/25/2019 python3.odp

    341/458

    341total'.py

    sing a Python function + Tdef total#nOers*)

    sO_so_far S &

    for nOer in nOers)

    sO_so_far =S nOer

    retrn sO_so_far

    print#total#[' " 3]**print#total#[9V4'6&]**print#total#[]**

    $ python3 tot+l.py

    6'&&

    se the functionmultiple times

  • 7/25/2019 python3.odp

    342/458

    342total".py

    &unctions? pri!ate names + ,def total#nOers*)

    sO_so_far S &

    for nOer in nOers)

    sO_so_far =S nOer

    retrn sO_so_far

    data S [' " 3]data_sO S total#data*pr


Recommended