0% found this document useful (0 votes)
92 views

Python Basics

som

Uploaded by

bokbokreonal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Python Basics

som

Uploaded by

bokbokreonal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Python as a Calculator

Arithmetic Operators
Operato r + * ** / // % Operation addition subtraction multiplication exponentiation di$ision integer di$ision modulo &remainder' Expressio n 11 + 56 23 52 4 * 5 2 ** 5 9 / 2 9 // 2 9 % 2 English description 11 plus 56 23 minus 52 4 multiplied b 5 2 to the po"er o# 5 9 di$ided b 2 9 di$ided b 2 9 mod 2 Resul t 67 -29 2! 32 4%5 4 1

Types int and float


( type is a set o# $alues and operations that can be per#ormed on those $alues% )"o o# * thon+s numeric t pes, int, integer -or example, 3. 4. 894. 0. -3. -18 float, #loating point number &an approximation to a real number' -or example, 5.6. 7.342. 53452.0. 0.0. -89.34. -9.5

Arithmetic Operator Precedence


/hen multiple operators are combined in a single expression. the operations are e$aluated in order o# precedence% Operator 00 - &negation' 0. 1. 11. 2 3 &addition'. &subtraction' *recedenc e highest

lo"est

Syntax and Semantics


Syntax, the rules that describe $alid combinations o# * thon s mbols Semantics, the meaning o# a combination o# * thon s mbols is the meaning o# an instruction 4 "hat a particular combination o# s mbols does "hen ou execute it%

Errors
( s ntax error occurs "hen "e an instruction "ith in$alid s ntax is executed% -or example,
>>> 3) + 2 * 4 SyntaxError in!ali" #yntax

( semantic error occurs "hen an instruction "ith in$alid semantics is executed% -or example,
>>> 89.4 / 0 $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,,- lin& 1- in 89.4 / 0 .&ro/i!i#ionError float "i!i#ion 'y 0&ro

Python and Computer Memory


Computer Memory
-or the purpose o# this course. ou ma thin5 o# computer memory as a long list o# storage locations "here each location is identi#ied "ith a uni6ue number and each location houses a $alue% )his uni6ue number is called a memory address% ) picall . "e "ill "rite memor addresses as a number "ith an 7id7 as a pre#ix to distinguish them #rom other numbers &#or example. i"201 is memor address 2!1'% 8ariables are a "a to 5eep trac5 o# $alues stored in computer memor % ( variable is a named location in computer memor % * thon 5eeps $ariables in a separate list #rom $alues% ( $ariable "ill contain a memor address. and that memor address contains the $alue% )he $ariable then re#ers to the $alue% * thon "ill pic5 the memor addresses #or ou%

Terminology
( $alue has a memor address% ( $ariable contains a memor address% ( $ariable re#ers to a $alue% ( $ariable points to a $alue% Example, 8alue 8.5 has memor address i"34% 8ariable #1o&2#i0& contains memor address i"34% )he $alue o# #1o&2#i0& is 8.5% #1o&2#i0& re#ers to $alue 8.5% #1o&2#i0& points to $alue 8.5%

Variables
Assignment statements
)he general #orm o# an assignment statement, !aria'l& 3 &x4r&##ion Example assignment statements,
>>> 'a#& 3 20

>>> 1&i51t 3 12 >>> ar&a 3 'a#& * 1&i51t / 2 >>> ar&a 120.0

)he rules #or executing an assignment statement, 1% E$aluate the expression% )his produces a memor address% 2% 9tore the memor address in the $ariable%

Variable names
)he rules #or legal * thon names, 1% :ames must start "ith a letter or 2% 2% :ames must contain onl letters. digits. and 2% -or * thon. in most situations. the con$ention is to use 4ot1ol&2%a#&%

Built-in unctions
unction Call
)he general #orm o# a #unction call, f6n%tion2na*&)ar56*&nt#) )he rules #or executing a #unction call, 1% E$aluate the arguments% 2% ;all the #unction. passing in the argument $alues% )erminolog , Argument, a $alue gi$en to a #unction Pass, to pro$ide to a #unction Call, as5 * thon to e$aluate a #unction Return, pass bac5 a $alue

Example #unction calls,


>>> a'#)-23) 23 >>> a'#)56.24) 56.24

unction dir
* thon has a set o# built-in #unctions% )o see the list o# built-in #unctions. run "ir)22'6iltin#22), >>> "ir)22'6iltin#22)7 'r/> 89:rit1*&ti%Error9- 9:##&rtionError99:ttri'6t&Error9- 9;a#&Ex%&4tion9- 9;6ff&rError9- 9;yt&#<arnin599/&4r&%ation<arnin59- 9E=+Error9- 9Elli4#i#9- 9En!iron*&ntError9-

9Ex%&4tion9- 9+al#&9- 9+loatin5>ointError9- 9+6t6r&<arnin599?&n&ratorExit9- 9@=Error9- 9@*4ortError9- 9@*4ort<arnin599@n"&ntationError9- 9@n"&xError9- 9A&yError9- 9A&y'oar"@nt&rr64t99Boo(64Error9- 9C&*oryError9- 9Da*&Error9- 9Don&9- 9Dot@*4l&*&nt&"99Dot@*4l&*&nt&"Error9- 9=SError9- 9=!&rfloEError99>&n"in5/&4r&%ation<arnin59- 9F&f&r&n%&Error9- 9F&#o6r%&<arnin599F6nti*&Error9- 9F6nti*&<arnin59- 9Sto4@t&ration9- 9SyntaxError99Syntax<arnin59- 9Sy#t&*Error9- 9Sy#t&*Exit9- 9$a'Error9- 9$r6&99$y4&Error9- 9Gn'o6n"Bo%alError9- 9Gni%o"&/&%o"&Error99Gni%o"&En%o"&Error9- 9Gni%o"&Error9- 9Gni%o"&$ran#lat&Error99Gni%o"&<arnin59- 9G#&r<arnin59- 9Hal6&Error9- 9<arnin599.&ro/i!i#ionError9- 929- 922'6il"2%la##229- 922"&'65229- 922"o%229922i*4ort229- 922na*&229- 9224a%(a5&229- 9a'#9- 9all9- 9any99a#%ii9- 9'in9- 9'ool9- 9'yt&array9- 9'yt&#9- 9%alla'l&9- 9%1r99%la##*&t1o"9- 9%o*4il&9- 9%o*4l&x9- 9%o4yri51t9- 9%r&"it#99"&lattr9- 9"i%t9- 9"ir9- 9"i!*o"9- 9&n6*&rat&9- 9&!al9- 9&x&%99&xit9- 9filt&r9- 9float9- 9for*at9- 9fro0&n#&t9- 95&tattr995lo'al#9- 91a#attr9- 91a#19- 91&l49- 91&x9- 9i"9- 9in46t9- 9int99i#in#tan%&9- 9i##6'%la##9- 9it&r9- 9l&n9- 9li%&n#&9- 9li#t99lo%al#9- 9*a49- 9*ax9- 9*&*ory!i&E9- 9*in9- 9n&xt9- 9o'I&%t9- 9o%t99o4&n9- 9or"9- 94oE9- 94rint9- 94ro4&rty9- 9J6it9- 9ran5&9- 9r&4r99r&!&r#&"9- 9ro6n"9- 9#&t9- 9#&tattr9- 9#li%&9- 9#ort&"99#tati%*&t1o"9- 9#tr9- 9#6*9- 9#64&r9- 9t64l&9- 9ty4&9- 9!ar#990i49K

unction help
)o get in#ormation about a particular #unction. call 1&l4 and pass the #unction as the argument% -or example,
>>> 1&l4)a'#) L&l4 on '6ilt-in f6n%tion a'# in *o"6l& '6iltin# a'#)...) a'#)n6*'&r) -> n6*'&r F&t6rn t1& a'#ol6t& !al6& of t1& ar56*&nt.

Optional arguments
<n the description o# #unction 4oE belo". the s6uare brac5ets around 8- 0K indicate that the third argument is optional,
>>> 1&l4)4oE) L&l4 on '6ilt-in f6n%tion 4oE in *o"6l& '6iltin# 4oE)...) 4oE)x- y8- 0K) -> n6*'&r <it1 tEo ar56*&nt#- &J6i!al&nt to x**y. <it1 t1r&& ar56*&nt#&J6i!al&nt to )x**y) % 0- '6t *ay '& *or& &ffi%i&nt )&.5. for lon5#).

-unction 4oE can be called "ith either t"o or three arguments,

>>> 4oE)2- 5) 32 >>> 4oE)2- 5- 3) 2

!e"ining unctions
unction !e"initions
)he general #orm o# a #unction de#inition,
"&f f6n%tion2na*&)4ara*&t&r#) 'o"y

"&f, a 5e "ord indicating a #unction de#inition #unction=name, the #unction name parameters, the parameter&s' o# the #unction. ! or more and are separated b a comma a parameter is a $ariable "hose $alue "ill be supplied "hen the #unction is called bod , 1 or more statements. o#ten ending "ith a r&t6rn statement Example o# a #unction de#inition,
"&f f)x) r&t6rn x ** 2

return statement
)he general #orm o# a r&t6rn statement,
r&t6rn &x4r&##ion

)he rules #or executing a r&t6rn statement, 1% E$aluate the expression% )his produces a memor address% 2% *ass bac5 that memor address to the caller% Exit the #unction%

unction Calls
-unction calls are expressions and the result can be stored in a $ariable% )he general #orm o# a #unction call,
f6n%tion2na*&)ar56*&nt#)

)he rules #or executing a #unction call, 1% E$aluate the arguments to produce memor addresses% 2% 9tore those memor addresses in the corresponding parameters% 3% Execute the bod o# the #unction% Example o# a #unction de#inition and #unction calls,
>>> "&f ar&a)'a#&- 1&i51t) r&t6rn 'a#& * 1&i51t / 2 >>> ar&a)3- 4) 6.0 >>> r&#6lt 3 ar&a)10- 7.45) >>> r&#6lt 37.25

Sa#ing your programs to $%py$ "iles


/e usuall sa$e our * thon programs in 7%p 7 #iles% ( #ile can contain multiple #unction de#initions and other statements% >e#ore calling a #unction #rom a 7%p 7 #ile in the shell in <?@E. ou need to #irst execute Run -A Run Bodule. or else the shell "ill not recogniCe the #unction call%

Type str& Strings in Python


String 'iteral
( string literal is a se6uence o# characters% <n * thon. this t pe is called #tr% 9trings in * thon start and end "ith a single 6uotes &9' or double 6uotes &,'% ( string can be made up o# letters. numbers. and special characters% -or example,
>>> 91&llo9 91&llo9 >>> 91oE ar& yo6M9 91oE ar& yo6M9 >>> 9#1ort- an" lon5-t&r*9 #1ort- an" lon5-t&r*

<# a string begins "ith a single 6uote. it must end "ith a single 6uote% )he same applies to double6uoted strings% Dou can not mix the t pe o# 6uotes%

Escape Se(uences
)o include a 6uote "ithin a string. use an escape character &N' be#ore it% Other"ise * thon interprets that 6uote as the end o# a string and an error occurs% -or example. the #ollo"ing code results in an error because * thon does not expect an thing to come a#ter the second 6uote,
>>> #tor*25r&&tin5 3 9EoE- yo69r& "ri44in5 E&t.9 SyntaxError in!ali" #yntax

)he escape sequence N9 indicates that the second 6uote is simpl a 6uote. not the end o# the string,
>>> #tor*25r&&tin5 3 9<oE- yo6N9r& "ri44in5 E&t.9 ,<oE- yo69r& "ri44in5 E&t.,

(n alternati$e approach is to use a double-6uoted string "hen including a a single-6uote "ithin it. or $ice-$ersa% 9ingle- and double-6uoted strings are e6ui$alent% -or example. "hen "e used double6uotes to indicate the beginning and end o# the string. the single-6uote in yo69r& no longer causes an error,
>>> #tor*25r&&tin5 3 ,<oE- yo69r& "ri44in5 E&t., ,<oE- yo69r& "ri44in5 E&t.,

String Operators
Expression ?escription #tr1 + #tr2 concatenate #tr1 and #tr1 #tr1 * int1 concatenate int1 copies o# #tr1 int1 * #tr1 concatenate int1 copies o# #tr1 :ote, concatenate means to Eoin together Example 4rint)9a'9 + 9%9) 4rint)9a9 * 5) 4rint)4 * 9'%9) Output a'% aaaaa '%'%'%'%

)he * and + operands obe b the standard precedence rules "hen used "ith strings% (ll other mathematical operators and operands result in a $y4&Error%

)nput*Output and str ormatting


unction print
* thon has a built-in #unction named 4rint that displa s messages to the user% -or example. the #ollo"ing #unction call displa s the string ,1&llo,,
>>> 4rint),1&llo,) 1&llo

<n the output abo$e. notice that 1&llo is displa ed "ithout the 6uotation mar5s% )he 6uotes are onl #or * thon+s internal string #ormatting and are not seen b the user% )he 4rint #unction ma also be called "ith a mathematical expression #or an argument% * thon e$aluates the mathematical expression #irst and then displa s the resulting $alue to the user% -or example,
>>> 4rint)3 + 7 - 3) 7

-inall . 4rint can ta5e in more than one argument% Each pair o# arguments is separated b a comma and a space is inserted bet"een them "hen the are displa ed% -or example,
>>> 4rint),1&llo,- ,t1&r&,) 1&llo t1&r&

return #s% print


+ecall& )he general #orm o# a r&t6rn statement,
r&t6rn expression

/hen a r&t6rn statement executes. the expression is e$aluated to produce a memor address% What is passed back to the caller? )hat memor address is passed bac5 to the caller% What is displayed? :othingF (n example o# r&t6rn,
>>> "&f #J6ar&2r&t6rn)n6*) r&t6rn n6* ** 2 >>> an#E&r2r&t6rn 3 #J6ar&2r&t6rn)4) >>> an#E&r2r&t6rn 16

)he general #orm o# a 4rint #unction call,


4rint)arguments)

/hen a 4rint #unction call is executed. the argument&s' are e$aluated to produce memor address&es'% What is passed back to the caller? :othingF What is displayed? )he $alues at those memor address&es' are displa ed on the screen% (n example o# 4rint,
>>> "&f #J6ar&24rint)n6*) 4rint),$1& #J6ar& of n6* i#,- n6* ** 2) >>> an#E&r24rint 3 #J6ar&24rint)4) $1& #J6ar& n6* i# 16 >>> an#E&r24rint >>>

unction input
)he #unction in46t is a built-in #unction that prompts the user to enter some input% )he program "aits #or the user to enter the input. be#ore executing the subse6uent instructions% )he $alue returned #rom this #unction is always a string% -or example,
>>> in46t),<1at i# yo6r na*&M ,) <1at i# yo6r na*&M O&n 9O&n9 >>> na*& 3 in46t),<1at i# yo6r na*&M ,) <1at i# yo6r na*&M O&n >>> na*& 9O&n9 >>> lo%ation 3 in46t),<1at i# yo6r lo%ationM ,) <1at i# yo6r lo%ationM $oronto >>> lo%ation

9$oronto9 >>> 4rint)na*&- ,li!&# in,- lo%ation) O&n li!&# in $oronto >>> n6*2%off&& 3 in46t),LoE *any %64# of %off&&M ,) LoE *any %64# of %off&&M 2 929

Operations on strings
Operation #tr1 + #tr2 #tr1 * int1 int1 * #tr1 ?escription concatenate #tr1 and #tr1 concatenate int1 copies o# #tr1 concatenate int1 copies o# #tr1 Example 4rint)9a'9 + 9%9) 4rint)9a9 * 5) 4rint)4 * 9'%9) Output a'% aaaaa '%'%'%'%

Triple-(uoted strings
/e ha$e used single- and double- 6uotes to represent strings% )he third string #ormat uses triple-6uotes and a triple-6uoted string cab span multiple lines% -or example,
>>> 4rint)999 LoE ar& yo6M999) LoE ar& yo6M

Escape Se(uences
* thon has a special character called an escape character, N% /hen the escape character is used in a string. the character #ollo"ing the escape character is treated di##erentl #rom normal% )he escape character together "ith the character that #ollo"s it is an escape sequence% )he table belo" contains some o# * thon+s commonl used escape se6uences% Escape 9e6uence Nn Nt NN N9 N, :ame ne"line &(9;<< line#eed @-' tab &(9;<< horiContal tab )(>' bac5slash &N' single 6uote &9' double 6uote &,' Example 4rint)999LoE ar& yo6M999) 4rint)93Nt4Nt59)
4rint)9NN9) 4rint)9"onN9t9) 4rint),L& #ay#- N,1iN,.,)

Output LoE ar& yo6M


3 N "on9t L& #ay#,1i,. 4 5

!ocstrings and unction help


>uilt-in #unction 1&l4 displa s the docstring #rom a #unction de#inition% -or example. consider this #unction,
"&f ar&a)'a#&- 1&i51t) ,,,)n6*'&r- n6*'&r) -> n6*'&r F&t6rn t1& ar&a of a trian5l& Eit1 "i*&n#ion# 'a#& an" 1&i51t. ,,, r&t6rn 'a#& * 1&i51t / 2

;alling 1&l4 on #unction ar&a produces this output,


>>> 1&l4)ar&a) L&l4 on f6n%tion ar&a in *o"6l& 22*ain22 ar&a)'a#&- 1&i51t) )n6*'&r- n6*'&r) -> n6*'&r F&t6rn t1& ar&a of a trian5l& Eit1 "i*&n#ion# 'a#& an" 1&i51t.

unction !esign +ecipe


The Six Steps
1% Examples /hat should our #unction doG ) pe a couple o# example calls% *ic5 a name &o#ten a $erb or $erb phrase', /hat is a short ans"er to 7/hat does our #unction do7G 2% Type Contract /hat are the parameter t pesG /hat t pe o# $alue is returnedG 3% ,eader *ic5 meaning#ul parameter names% 4% !escription Bention e$er parameter in our description% ?escribe the return $alue% 5% Body /rite the bod o# our #unction% 6% Test Run the examples%

Applying the !esign +ecipe


The problem& )he Hnited 9tates measures temperature in -ahrenheit and ;anada measures it in ;elsius% /hen tra$elling bet"een the t"o countries it helps to ha$e a con$ersion #unction% /rite a #unction that con$erts #rom -ahrenheit to ;elsius% 1% Examples
>>> %on!&rt2to2%%&l#i6#)32) 0 >>> %on!&rt2to2%&l#i6#)212) 100

2% Type Contract
)n6*'&r) -> n6*'&r

3% ,eader
"&f %on!&rt2to2%&l#i6#)fa1r&n1&it)

4% !escription
F&t6rn t1& n6*'&r of P&l#i6# "&5r&&# &J6i!al&nt to fa1r&n1&it "&5r&&#.

5% Body
r&t6rn )fa1r&n1&it - 32) * 5 / 9

6% Test
F6n t1& &xa*4l&#.

Putting it all together&


"&f %on!&rt2to2%&l#i6#)fa1r&n1&it) 999 )n6*'&r) -> n6*'&r F&t6rn t1& n6*'&r of P&l#i6# "&5r&&# &J6i!al&nt to fa1r&n1&it "&5r&&#. >>> %on!&rt2to2%%&l#i6#)32) 0 >>> %on!&rt2to2%&l#i6#)212) 100 999 r&t6rn )fa1r&n1&it - 32) * 5 / 9

unction +euse
Calling "unctions -ithin other "unction de"initions
The problem& ;alculate the semi-perimeter o# a triangle% The approach& -unction #&*i4&ri*&t&r calls #unction 4&ri*&t&r%
"&f 4&ri*&t&r)#i"&1- #i"&2- #i"&3) 999)n6*'&r- n6*'&r- n6*'&r) -> n6*'&r F&t6rn t1& 4&ri*&t&r of a trian5l& Eit1 #i"&# of l&n5t1 #i"&1- #i"&2 an" #i"&3. >>> 4&ri*&t&r)3- 4- 5) 12 >>> 4&ri*&t&r)10.5- 6- 9.3) 25.8 999 r&t6rn #i"&1 + #i"&2 + #i"&3 "&f #&*i4&ri*&t&r)#i"&1- #i"&2- #i"&3) 999)n6*'&r- n6*'&r- n6*'&r) -> float F&t6rn t1& 4&ri*&t&r of a trian5l& Eit1 #i"&# of l&n5t1 #i"&1- #i"&2 an" #i"&3. >>> #&*i4&ri*&t&r)3- 4- 5) 6.0 >>> #&*i4&ri*&t&r)10.5- 6- 9.3) 12.9 999 return perimeter(side1, side2, side3) / 2

Calling "unctions -ithin other "unction calls


The problem& One triangle has a base o# length 3%I and a height o# length 7%!% ( second triangle has a base o# length 3%5 and a height o# length 6%I% ;alculate "hich o# t"o triangles+ areas is biggest% The approach& *ass calls to #unction ar&a as arguments to built-in #unction *ax%
*ax)ar&a)3.8- 7.0)- ar&a)3.5- 6.8))

Type bool& Booleans in Python


Boolean #alues
)he * thon t pe 'ool has t"o $alues, $r6& and +al#&%

Comparison operators
)he comparison operators ta5e t"o $alues and produce a >oolean $alue% ?escription Operator Example Result o# example

less than greater than e6ual to greater than or e6ual to less than or e6ual to not e6ual to

7 > 33 >3 73 Q3

3 3 3 3 3 3

7 4 > 4 33 4 >3 4 73 4 Q3 4

$r6& +al#& +al#& +al#& $r6& $r6&

'ogical operators
)here are also three logical operators that produce >oolean $alues, an". or. and not% ?escription not and or Operator not an" or Example not )80 >3 50) )80 >3 50) an" )70 73 50) )80 >3 50) or )70 73 50) Result o# example +al#& +al#& $r6&

The and 'ogic Table


)he an" operator produces $r6& i# and onl i# both expressions are $r6&% (s such. i# the #irst operand is +al#&. the second condition "ill not e$en be chec5ed. because it is alread 5no"n that the expression "ill produce +al#&% expr $r6& $r6& +al#& +al#& expr! $r6& +al#& $r6& +al#& expr an" expr! $r6& +al#& +al#& +al#&

The or 'ogic Table


)he or operator e$aluates to $r6& i# and onl i# at least one operand is $r6&% (s such. i# the #irst operand is $r6&. the second condition "ill not e$en be chec5ed. because it is alread 5no"n that the expression "ill produce $r6&% expr $r6& $r6& +al#& +al#& expr! $r6& +al#& $r6& +al#& expr or expr! $r6& $r6& $r6& +al#&

The not 'ogic Table


)he not operator e$aluates to $r6& i# and onl i# the operand is +al#&% expr $r6& not expr +al#&

+al#& $r6& ?ouble-negation can be simpli#ied% -or example. the expression not not )4 33 5) can be simpli#ied to 4 33 5%

Order o" Precedence "or 'ogical Operators


)he order o# precedence #or logical operators is, not. an". then or% /e can o$erride precedence using parentheses and parentheses can also be added to ma5e things easier to read and understand% -or example. the not operator is applied be#ore the or operator in the #ollo"ing code,
>>> 5ra"& 3 80 >>> 5ra"&2 3 90 >>> not 5ra"& >3 50 or 5ra"&2 >3 50 $r6&

*arentheses can be added to ma5e this clearer, )not 5ra"& >3 50) or )5ra"&2 >3 50) (lternati$el . parentheses can be added to change the order o# operations, not ))5ra"& >3 50) or )5ra"&2 >3 50))

Con#erting bet-een int. str. and float


str
>uiltin #unction #tr ta5es an $alue and returns a string representation o# that $alue%
>>> #tr)3) 939 >>> #tr)47.6) 947.69

int
>uiltin #unction int ta5es a string containing onl digits &possibl "ith a leading minus sign -' and returns the int that represents% -unction int also con$erts float $alues to integers b thro"ing a"a the #ractional part%
>>> int)9123459) 12345 >>> int)9-9989) -998 >>> int)-99.9) -99

<# #unction int is called "ith a string that contains an thing other than digits. a Hal6&Error happens%
>>> int)9-99.99) $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,7#t"in>,- lin& 1- in 7*o"6l&> Hal6&Error in!ali" lit&ral for int)) Eit1 'a#& 10

9-99.99

"loat
>uiltin #unction float ta5es a string containing onl digits and Cero or one decimal points &possibl "ith a leading minus sign -' and returns the float that represents% -unction float also con$erts int $alues to floats%
>>> float)9-43.29) -43.2 >>> float)94329) 432.0 >>> float)4) 4.0

<# #unction float is called "ith a string that can+t be con$erted. a Hal6&Error happens%
>>> float)9-9.9.99) $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,7#t"in>,- lin& 1- in 7*o"6l&> Hal6&Error %o6l" not %on!&rt #trin5 to float

9-9.9.99

)mport& /sing 0on-Builtin unctions


Modules
* thon contains man #unctions. but not all o# them are immediatel a$ailable as builtin #unctions% <nstead o# being a$ailable as builtins. some #unctions are sa$ed in di##erent modules% ( module is a #ile containing #unction de#initions and other statements% /e ma also de#ine our o"n modules "ith our o"n #unctions%

import
<n order to gain access to the #unctions in a module. "e must import that module% )he general #orm o# an import statement is,
i*4ort *o"6l&2na*&

)o access a #unction "ithin a module. "e use,


*o"6l&2na*&.f6n%tion2na*&

-or example. "e can import the * thon module *at1 and call the #unction #Jrt #rom it,
i*4ort *at1 "&f ar&a2)#i"&1- #i"&2- #i"&3) #&*i 3 #&*i4&ri*&t&r)#i"&1- #i"&2- #i"&3) ar&a 3 *at1.#Jrt)#&*i * )#&*i - #i"&1) * )#&*i - #i"&2) * )#&*i - #i"&3)) r&t6rn ar&a

<n addition to importing * thon+s modules. "e can also import the modules that "e "rite% -or example. to use the #unctions #rom trian5l&.4y &#rom the $ideo' in another module. "e "ould i*4ort trian5l&% ( module being imported should be in the same director as the module importing it%

The if statement
<# statements can be used to control "hich instructions are executed% Jere is the general #orm,
if &x4r&##ion1 'o"y1 8&lif &x4r&##ion2 'o"y2K 8&l#& 'o"yDK 0 or *or& %la6#&# 0 or 1 %la6#&

&lif stands #or 7else i#7. so this #orms a chain o# conditions% )o execute an if statement. e$aluate each expression in order #rom top to bottom% <# an expression produces $r6&. execute the bod o# that clause and then s5ip the rest open 3he if statement% <# there is an &l#&. and none o# the expressions produce $r6&. then execute the bod o# the &l#&% -or example. gi$en this #unction,
"&f r&4ort2#tat6#)#%1&"6l&"2ti*&- &#ti*at&"2ti*&) ,,, )float- float) -> #tr ,,, if #%1&"6l&"2ti*& 33 &#ti*at&"2ti*& r&t6rn 9on ti*&9 &lif #%1&"6l&"2ti*& > &#ti*at&"2ti*& r&t6rn 9&arly9 &l#& r&t6rn 9"&lay&"9

<n the shell,


>>> r&4ort2#tat6#)14.3- 14.3) 9on ti*&9 >>> r&4ort2#tat6#)12.5- 11.5) 9&arly9 >>> r&4ort2#tat6#)9.0- 9.5) 9"&lay&"9

A note on None
/hen execution o# a #unction bod ends "ithout ha$ing executed a r&t6rn statement. the #unction returns $alue Don&% )he t pe o# Don& is Don&$y4&% -or example. consider this #unction,
"&f r&4ort2#tat6#)#%1&"6l&"2ti*&- &#ti*at&"2ti*&) ,,, )float- float) -> #tr F&t6rn t1& fli51t #tat6# )on ti*&- &arly- "&lay&") for a fli51t t1at Ea# #%1&"6l&" to arri!& at #%1&"6l&"2ti*&"- '6t i# noE &#ti*at&" to arri!& at &#ti*at&"2ti*&. >r&-%on"ition 0.0 73 #%1&"6l&"2ti*& 7 24.0 an" 0.0 73 &#ti*at&"2ti*& 7 24.0

>>> r&4ort2#tat6#)14.3- 14.3) 9on2ti*&9 >>> r&4ort2#tat6#)12.5- 11.5) 9&arly9 >>> r&4ort2#tat6#)9.0- 9.5)

9"&lay&"9 ,,, if #%1&"6l&"2ti*& 33 &#ti*at&"2ti*& r&t6rn 9on ti*&9

<n the shell,


>>> r&4ort2#tat6#)14-3- 14.3) 9on ti*&9 >>> r&4ort2#tat6#)12.5- 11.5) >>> 4rint)r&4ort2#tat6#)12.5- 11.5)) Don&

>ecause the t pe o# Don& is Don&$y4&. not #tr. this brea5s the ) pe ;ontract% )o #ix this. "e "ould need to complete the rest o# the #unction%

0o if +e(uired
<t is common #or ne" programmers to "rite code li5e the #ollo"ing,
"&f i#2&!&n)n6*) ,,, )int) -> 'ool F&t6rn E1&t1&r n6* i# &!&n. ,,, if n6* % 2 33 0 r&t6rn $r6& &l#& r&t6rn +al#&

)his "or5s. but is st listicall 6uestionable% <t+s also more t ping and reading than is necessar F n6* % 2 33 0 alread produces $r6& or +al#&. so that expression can be used "ith the r&t6rn statement,
"&f i#2&!&n)n6*) ,,, )int) -> 'ool F&t6rn E1&t1&r n6* i# &!&n. ,,, r&t6rn n6* % 2 33 0

Structuring if Statements
if-elif #s% if-if
(n if statement "ith an &lif clause is a single statement% )he expressions are e$aluated #rom top to bottom until one produces $r6& or until there are no expressions le#t to e$aluate% /hen an expression

produces $r6&. the bod associated "ith it is executed and then the if statement exits% (n subse6uent expressions are ignored% -or example,
5ra"&1 3 70 5ra"&2 3 80 if 5ra"&1 >3 50 4rint)9Ro6 4a##&" a %o6r#& Eit1 5ra"& &lif 5ra"&2 >3 50 4rint)9Ro6 4a##&" a %o6r#& Eit1 5ra"& 9- 5ra"&1) 9- 5ra"&2)

)he if statement condition &5ra"&1 >3 50' e$aluates to $r6&. so the bod associated "ith the if is executed and then the if exits% )he &lif condition is not e$en e$aluated in this case% <t is possible #or if statements to appear one a#ter another in a program% (lthough the are be adEacent to each other. the are completel independent o# each other and it is possible #or the bod o# each if to be executed% -or example,
5ra"&1 3 70 5ra"&2 3 80 if 5ra"&1 >3 50 4rint)9Ro6 4a##&" a %o6r#& Eit1 5ra"& if 5ra"&2 >3 50 4rint)9Ro6 4a##&" a %o6r#& Eit1 5ra"& 9- 5ra"&1) 9- 5ra"&2)

<n the program abo$e. the condition associated "ith the #irst if statement &5ra"&1 >3 50' produces $r6&. so the bod associated "ith it is executed% )he condition associated "ith the second if statement &5ra"&2 >3 50' also produces $r6&. so the bod associated "ith it is also executed%

0ested ifs
<t is possible to place an if statement "ithin the bod o# another if statement% -or example,
if 4r&%i4itation if t&*4&rat6r& > 0 4rint)9;rin5 yo6r 6*'r&llaQ9) &l#& 4rint)9<&ar yo6r #noE 'oot# an" Eint&r %oatQ)

)he statement abo$e can be simpli#ied b remo$ing some o# the nesting% )he message 9;rin5 yo6r 6*'r&llaQ9 is printed onl "hen both o# the if statement conditions are $r6&% )he message 9<&ar yo6r #noE 'oot# an" Eint&r %oatQ9 is printed onl "hen the outer if condition is $r6&. but the inner if condition is +al#&% )he #ollo"ing is e6ui$alent to the code abo$e,
if 4r&%i4itation an" t&*4&rat6r& > 0 4rint)9;rin5 yo6r 6*'r&lla9) &lif 4r&%i4itation 4rint)9<&ar yo6r #noE 'oot# an" Eint&r %oatQ9)

More str Operators


String Comparisons
)he e6ualit and ine6ulit operators can be applied to strings,
>>> 9a9 33 9a9 $r6& >>> 9ant9 33 9a%&9 +al#& >>> 9a9 33 9'9 +al#& >>> 9a9 Q3 9'9 $r6&

/e can compare t"o strings #or their dictionar order. comparing them letter b letter,
>>> 9a'ra%a"a'ra9 7 9a%&9 $r6& >>> 9a'ra%a"a'ra9 > 9a%&9 +al#& >>> 9a9 73 9a9 $r6& >>> 9:9 7 9;9 $r6&

;apitaliCation matters. and capital letters are less than lo"ercase letters,
>>> 9a9 Q3 9:9 $r6& >>> 9a9 7 9:9 +al#&

E$er letter can be compared,


>>> 9-9 7 939 $r6&

/e can compare a string and an integer #or e6ualit ,


>>> 9#9 33 3 +al#&

/e can+t compare $alues o# t"o di##erent t pes #or ordering,


>>> 9#9 73 3 $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,7#t"in>,- lin& 1- in 7*o"6l&>> $y4&Error 6nor"&ra'l& ty4&# #tr)) 73 int))

Testing or Substrings
)he operator in chec5s "hether a string appears an "here inside another one &that is. "hether a string is a substring o# another'%
>>> 9%9 in 9a&io69

+al#& >>> 9%a"9 in 9a'ra%a"a'ra9 $r6& >>> 90oo9 in 9oo0&9 +al#&

String length& "unction len


)he builtin #unction l&n returns the number o# characters in a string,
>>> l&n)99) 0 >>> l&n)9a'ra%a"a'ra9) 11 >>> l&n)9;Ea9 + 91a9 * 10) 23

Summary
?escription e6ualit ine6ualit less than greater than less than or e6ual greater than or e6ual contains length o# #tr s Operato r 33 Q3 7 > 73 >3 in l&n)# ) Example 9%at9 33 9%at9 9%at9 Q3 9Pat9 9:9 7 9a9 9a9 > 9:9 9a9 73 9a9 9a9 >3 9:9 9%a"9 in 9a'ra%a"a'ra9 l&n),a'%,) Result o# example $r6& $r6& $r6& $r6& $r6& $r6& $r6& 3

str& indexing and slicing


)ndexing
(n index is a position "ithin the string% *ositi$e indices count #rom the le#t-hand side "ith the #irst character at index !. the second at index 1. and so on% :egati$e indices count #rom the right-hand side "ith the last character at index -1. the second last at index -2. and so on% -or the string ,B&arn to >ro5ra*,. the indices are,

)he #irst character o# the string is at index ! and can be accessed using this brac5et notation,
>>> #80K 9B9

>>> #81K 9&9

:egati$e indices are used to count #rom the end &#rom the right-hand side',
>>> #8-1K 9*9 >>> #8-2K 9a9

Slicing
/e can extract more than one character using slicing% ( slice is a substring #rom the start index up to but not including the end index% -or example,
>>> #80 5K 9B&arn9 >>> #86 8K 9to9 >>> #89 16K 9>ro5ra*9

Bore generall . the end o# the string can be represented using its length,
>>> #89 l&n)#)K 9>ro5ra*9

)he end index ma be omitted entirel and the de#ault is l&n)#),


>>> #89 K 9>ro5ra*9

9imilarl . i# the start index is omitted. the slice starts #rom index !,
>>> #8 9B&arn >>> #8 9B&arn K to >ro5ra*9 8K to9

:egati$e indices can be used #or slicing too% )he #ollo"ing three expressions are e6ui$alent,
>>> #81 8K 9&arn to9 >>> #81 -8K 9&arn to9 >>> #8-15 -8K 9&arn to9

Modi"ying Strings
)he slicing and indexing operations do not modi# the string that the act on. so the string that # re#ers to is unchanged b the operations abo$e% <n #act. "e cannot change a string% Operations li5e the #ollo"ing result in errors,
>>> #86K 3 9"9 $ra%&'a%( )*o#t r&%&nt %all la#t) +il& 7,4y#1&llS19,- lin& 1- in 7*o"6l&> #86K 3 9"9

$y4&Error

9#tr9 o'I&%t "o&# not #644ort it&* a##i5n*&nt

<magine that "e "ant to change string # to re#er to 9B&arn&" to >ro5ra*9% )he #ollo"ing expression e$aluates to that 9B&arn&" to >ro5ra*9, #8 5K + 9&"9 + #85 K 8ariable # gets the ne" string, # 3 #8 5K + 9&"9 + #85 K :otice that the string that # originall re#erred to "as not modi#ied, strings cannot be modi#ied% <nstead a ne" string "as created and # "as changed to point to that string%

str Methods& unctions )nside Ob1ects


Methods
( method is a #unction inside o# an obEect% )he general #orm o# a method call is, o'I&%t.*&t1o")ar56*&nt#)

String Methods
;onsider the code,
>>> E1it&2ra''it 3 ,@9* lat&Q @9* lat&Q +or a !&ry i*4ortant "at&Q,

)o #ind out "hich methods are inside strings. use the #unction "ir,
>>> "ir)E1it&2ra''it) 8922a""229- 922%la##229- 922%ontain#229- 922"&lattr229- 922"o%229- 922&J229922for*at2299225&229- 9225&tattri'6t&229-9225&tit&*229- 9225&tn&Ear5#229- 9225t2299221a#1229- 922init229922it&r229- 922l&229- 922l&n229- 922lt229- 922*o"229- 922*6l229- 922n&229922n&E229- 922r&"6%&229922r&"6%&2&x229- 922r&4r229- 922r*o"229- 922r*6l229- 922#&tattr229- 922#i0&of229922#tr229922#6'%la##1oo(229- 9%a4itali0&9- 9%&nt&r9- 9%o6nt9- 9&n%o"&9- 9&n"#Eit199&x4an"ta'#9- 9fin"99for*at9- 9for*at2*a49- 9in"&x9- 9i#aln6*9- 9i#al41a9- 9i#"&%i*al9- 9i#"i5it99i#i"&ntifi&r99i#loE&r9- 9i#n6*&ri%9- 9i#4rinta'l&9- 9i##4a%&9- 9i#titl&9- 9i#644&r9- 9Ioin99lI6#t9- 9loE&r99l#tri49- 9*a(&tran#9- 94artition9- 9r&4la%&9- 9rfin"9- 9rin"&x9- 9rI6#t99r4artition9- 9r#4lit99r#tri49- 9#4lit9- 9#4litlin&#9- 9#tart#Eit19- 9#tri49- 9#Ea4%a#&9- 9titl&99tran#lat&9- 9644&r990fill9K

*assing #tr as an argument to "ir gets the same result,


>>> "ir)#tr)

-or man o# the string methods. a ne" string is returned% 9ince strings are immutable. the original

string is unchanged% -or example. a lo"ercase $ersion o# the #tr that E1it&2ra''it re#ers to is returned "hen the method loE&r is called,
>>> >>> >>> >>> E1it&2ra''it.loE&r)) ,i9* lat&Q i9* lat&Q for a !&ry i*4ortant "at&Q, E1it&2ra''it ,@9* lat&Q @9* lat&Q +or a !&ry i*4ortant "at&Q,

)o get in#ormation about a method. such as the loE&r method. do the #ollo"ing,
>>> 1&l4)#tr.loE&r)

for loop o#er str


or 'oops
)he general #orm o# a #or loop o$er a string is,
for !aria'l& in #tr 'o"y

)he $ariable re#ers to each character o# the string in turn and executes the bod o# the loop #or each character% -or example,
>>> # 3 9y&#t&r"ay9 >>> for %1ar in # ... 4rint)%1ar) ... y & # t & r " a y

Accumulator pattern& numeric accumulator


;onsider the code belo". in "hich the $ariable n6*2!oE&l# is an accumulator,
"&f %o6nt2!oE&l#)#) ,,, )#tr) -> int F&t6rn t1& n6*'&r of !oE&l# in #. /o not tr&at l&tt&r y a# a !oE&l >>> %o6nt2!oE&l#)9La44y :nni!&r#aryQ9) 5 >>> %o6nt2!oE&l#)9xy09) 0 ,,,

n6*2!oE&l# 3 0 for %1ar in # if %1ar in 9a&io6:E@=G9 n6*2!oE&l# 3 n6*2!oE&l# + 1 r&t6rn n6*2!oE&l#

)he loo4 in the #unction abo$e "ill loop o$er each character that # re#ers to. in turn% )he bod o# the loop is executed #or each character. and "hen a character is a $o"el. the if condition is $r6& and the $alue that n6*2!oE&l# re#ers to is increased b one% )he $ariable n6*2!oE&l# is an accumulator. because it accumulates in#ormation% <t starts out re#erring to the $alue 0 and b the end o# the #unction it re#ers to the number o# $o"els in #%

Accumulator pattern& string accumulator


<n the #ollo"ing #unction. the $ariable !oE&l# is also an accumulator,
"&f %oll&%t2!oE&l#)#) ,,, )#tr) -> #tr F&t6rn t1& !oE&l# fro* #. y a# a !oE&l. /o not tr&at t1& l&tt&r

>>> %oll&%t2!oE&l#)9La44y :nni!&r#aryQ9) 9a:i&a9 >>> %oll&%t2!oE&l#)9xy09) 99 ,,, !oE&l# 3 99 for %1ar in # if %1ar in 9a&io6:E@=G9 !oE&l# 3 !oE&l# + %1ar r&t6rn !oE&l#

8ariable !oE&l# initiall re#ers to the empt string. but o$er the course o# the #unction it accumulates the $o"els #rom #%

)!'E2s !ebugger
!ebug Control
)he * thon 8isualiCer has limitations, it does not allo" import statements. and it stops tracing a#ter 3!! steps% <?@E comes "ith a debugger. "hich is a tool that "or5s a lot li5e the $isualiCer but "ithout the prett pictures% )o run a program in <?@E+s debugger. the steps are, 1% Ba5e sure the * thon 9hell "indo" is on top and select ?ebug-A?ebugger% )his opens a "indo" called 7?ebug ;ontrol7%

2% ;hec5 the chec5box #or 9ource% 3% Open the * thon #ile "here ou ha$e sa$ed our program% 4% 9elect Run-ARun Bodule% )his "ill change the contents o# ?ebug ;ontrol%

/nderstanding The !ebug 3indoSt&4 is li5e +orEar" in the $isualiCer, it executes the current instruction% /e clic5 St&4 to 7step7 through the program% )he ?ebug ;ontrol "indo" "ill highlight the current line being executed% <t "ill also sho" the current $ariables in the 7@ocals7 pane% )he middle pane sho"s the current stac5 #rames and the current lines o# code #or each% /e can s"itch bac5 and #orth bet"een them to see the $ariables%

while loops
)he general #orm o# a E1il& loop,
E1il& expression statements

)he E1il& condition. n6* 7 100. is e$aluated. and i# it is $r6& the statements in the loop bod are executed% )he loop condition is rechec5ed and i# #ound to be $r6&. the bod executes again% )his continues until the loop condition is chec5ed and is +al#&% -or example,
>>> n6* 3 2 >>> E1il& n6* 7 100 n6* 3 n6* * 2 4rint)n6*) 4 8 16 32 64 128

<n the example abo$e. there are 6 iterations, the loop bod executes 6 times%

'oops Conditions and 'a4y E#aluation


The problem, print the characters o# #tr #. up to the #irst $o"el in #% )he #irst attempt at sol$ing this problem "or5s nicel "hen # contains one or more $o"el. but results in an error i# there are no $o"els in #,
>>> i 3 0 >>> # 3 9xy09 >>> E1il& not )#8iK in 9a&io6:E@=G9) 4rint)#8iK) i 3 i + 1 x y 0 $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,74y#1&llS73>,- lin& 1- in 7*o"6l&>

E1il& not )#8iK in 9a&io6:E@=G9) @n"&xError #trin5 in"&x o6t of ran5&

<n the code abo$e. the error occurs "hen # is indexed at i and i is outside o# the range o# $alid indices% )o pre$ent this error. add an additional condition is added to ensure that i is "ithin the range o# $alid indices #or #,
>>> i 3 0 >>> # 3 9xy09 >>> E1il& i 7 l&n)#) an" not )#8iK in 9a&io6:E@=G9) 4rint)#8iK) i 3 i + 1 x y 0

>ecause * thon e$aluates the an" using laC e$aluation. i# the #irst operand is +al#&. then the expression e$aluates to +al#& and the second operand is not e$en e$aluated% )hat pre$ents the @n"&xError #rom occurring%

Comments
The 3hy and ,o- o" Comments
(s our programs get longer and more complicated. some additional English explanation can be used to help ou and other programmers read our code% )hese explanations called comments document our code. much the "a docstrings document our #unctions% ( comment begins "ith the number sign character &S' and goes until the end o# the line% One name #or this character is the hash character% * thon ignores an lines that start "ith this character% ;omments are intended #or programmers to read. and are usuall there to explain the purpose o# a #unction. as "ell as to describe relationships bet"een our $ariables% ;omments are to help ou. and an one else "ho is reading1using our code. to remember or understand the purpose o# a gi$en $ariable or #unction in a program%

Type list
O#er#ieOur programs "ill o#ten "or5 "ith collections o# data% One "a to store these collections o# data is using * thon+s t pe li#t% )he general #orm o# a list is,
8expr1- expr2- ...- exprNK

-or example. here is a list o# three grades,

5ra"&# 3 880- 90- 70K

'ist Operations
@i5e strings. lists can be indexed,
>>> 5ra"&#80K 80 >>> 5ra"&#81K 90 >>> 5ra"&#82K 70

@ists can also be sliced. using the same notation as #or strings,
>>> 5ra"&#80 2K 880- 90K

)he in operator can also be applied to chec5 "hether a $alue is an item in a list%
>>> 90 in 5ra"&# $r6& >>> 60 in 5ra"&# +al#&

9e$eral o# * thon+s built-in #unctions can be applied to lists. including,


>>> 3 >>> 70 >>> 90 >>> 240

l&n)li#t), return the length o# li#t% *in)li#t), return the smallest element in li#t% *ax)li#t), return the largest element in li#t% #6*)li#t), return the sum o# elements o# li#t &"here list items must be numeric'%

-or example. here are some calls to those built-in #unctions,


l&n)5ra"&#) *in)5ra"&#) *ax)5ra"&#) #6*)5ra"&#)

Types o" list elements


@ists elements ma be o# an t pe% -or example. here is a li#t of #tr,
#6'I&%t# 3 89'io9- 9%#9- 9*at19- 91i#tory9K

@ists can also contain elements o# more than one t pe% -or example. a street address can be represented b a li#t of 8int- #trK,
#tr&&t2a""r&## 3 810- 9Cain Str&&t9K

for loops o#er list


9imilar to looping o$er the characters o# a string. it is possible to iterate o$er the elements o# a list% -or example,
>>> for 5ra"& in 5ra"&# 4rint)5ra"&) 80 90 70

)he general #orm o# a for loop o$er a li#t is,


for variable in list body

list Methods
Methods
( method is a #unction inside an obEect% Dou can #ind out the methods in t pe li#t b t ping "ir)li#t)%

Modi"ying 'ists
)he table belo" contains methods that modi# lists% Bethod li#t.a44&n")o 'I&%t) ?escription (ppend o'I&%t to the end o# list% Example
>>> %olo6r# 3 89y&lloE9- 9'l6&9K >>> %olo6r#.a44&n")9r&"9) >>> 4rint)%olo6r#) 89y&lloE9- 9'l6&9- 9r&"9K >>> %olo6r#.&xt&n")894in(9- 95r&&n9K) >>> 4rint)%olo6r#) 89y&lloE9- 9'l6&9- 9r&"9- 94in(995r&&n9K >>> %olo6r#.4o4)) 95r&&n9 >>> 4rint)%olo6r#) 89y&lloE9- 9'l6&9- 9r&"9- 94in(9K >>> %olo6r#.4o4)2) 9r&"9 >>> 4rint)%olo6r#) 89y&lloE9- 9'l6&9- 94in(9K

li#t.&xt&n")l i#t)

(ppend the items in the list parameter to the list%

li#t.4o4)8in" &xK)

Remo$e the item at the end o# the listK optional index to remo$e #rom an "here%

li#t.r&*o!&)o 'I&%t)

>>> %olo6r#.r&*o!&)95r&&n9) Remo$e the #irst $ra%&'a%( )*o#t r&%&nt %all la#t) occurrence o# the +il& ,74y#1&llS10>,- lin& 1- in obEectK error i# not there% 7*o"6l&> %olo6r#.r&*o!&)95r&&n9) Hal6&Error li#t.r&*o!&)x) x not in li#t

>>> %olo6r#.r&*o!&)94in(9) >>> 4rint)%olo6r#) 89y&lloE9- 9'l6&9K >>> 5ra"&# 3 895- 65- 75- 85K >>> 5ra"&#.r&!&r#&)) >>> 4rint)5ra"&#) 885- 75- 65- 95K >>> 5ra"&#.#ort)) >>> 4rint)5ra"&#) 865- 75- 85- 95K >>> 5ra"&#.in#&rt)2- 80) >>> 4rint)5ra"&#) 865- 75- 80- 85- 95K

li#t.r&!&r#&) )

Re$erse the list%

li#t.#ort)) li#t.in#&rt)i nt- o'I&%t)

9ort the list #rom smallest to largest% <nsert obEect at the gi$en index. mo$ing items to ma5e room%

5etting )n"ormation "rom 'ists


)he table belo" contains methods that return in#ormation about lists% Bethod ?escripti on Return the number o# times obEect occurs in list% Return the index o# the #irst occurrenc e o# obEectK error i# not there% Example

li#t.%o6nt )o'I&%t)

>>> l&tt&r# 3 89a9- 9a9- 9'9- 9%9K >>> l&tt&r#.%o6nt)9a9) 2

li#t.in"&x )o'I&%t)

>>> l&tt&r#.in"&x)9a9) 0 >>> l&tt&r#.in"&x)9"9) $ra%&'a%( )*o#t r&%&nt %all la#t) +il& ,74y#1&llS24>,- lin& 1- in 7*o"6l&> l&tt&r#.in"&x)9"9) Hal6&Error 9"9 i# not in li#t

Mutability and Aliasing


Mutability
/e sa that lists are mutable, the can be modi#ied% (ll the other t pes "e ha$e seen so #ar &#tr. int. float and 'ool' are immutable, the cannot be modi#ied% Jere are se$eral examples o# lists being modi#ied,

>>> %la##&# 3 89%1&*9- 9'io9- 9%#9- 9&n59K >>> >>> S El&*&nt# %an '& a""&" >>> %la##&#.a44&n")9*at19) >>> %la##&# 89%1&*9- 9'io9- 9%#9- 9&n59- 9*at19K >>> >>> S El&*&nt# %an '& r&4la%&" >>> %la##&#81K 3 9#o%9 >>> %la##&# 89%1&*9- 9#o%9- 9%#9- 9&n59- 9*at19K >>> >>> S El&*&nt# %an '& r&*o!&" >>> %la##&#.4o4)) 9*at19 >>> %la##&# 89%1&*9- 9#o%9- 9%#9- 9&n59K

Aliasing
;onsider the #ollo"ing code,
>>> >>> >>> >>> 11l#t1 3 811- 12- 13- 14- 15- 16- 17K l#t2 3 l#t1 l#t18-1K 3 18 l#t2 12- 13- 14- 15- 16- 18K

(#ter the second statement executes. l#t1 and l#t2 both re#er to the same list% /hen t"o $ariables re#er to the same obEects. the are aliases% <# that list is modi#ied. both o# l#t1 and l#t2 "ill see the change%

+ange
The Built-in unction& +ange
* thon has a built-in #unction called ran5& that is use#ul to use "hen ou "ant to generate a se6uence o# numbers% Dou can t pe 1&l4)ran5&) in <?@E i# ou e$er need a reminder% )he example belo" "ill print the integers ! to 9. inclusi$e%
for i in ran5&)10) 4rint )i)

)he #orm o# ran5& is,


ran5&)8#tart-K #to48- #t&4K) r&t6rn a !irt6al #&J6&n%& of n6*'&r# fro* #tart to #to4 'y #t&4

Applications o" +ange


)here are other options ou can speci# to ran5&% One option is to let range generate the numbers corresponding to indices o# a string or a list%
# 3 9%o*46t&r #%i&n%&9 for i in ran5&)l&n)#)) 4rint)i)

Dou can also tell ran5& "hat index to start at% -or instance. the example belo" starts at index 1 &as opposed to the de#ault "hich is !'%
for i in ran5&)1- l&n)#)) 4rint)i)

Dou can e$en speci# the 7step7 #or ran5&% )he de#ault stepping siCe is 1. "hich means that numbers increment b 1% )he example belo" starts at index 1 and its step siCe is there &goes to e$er third index'%
for i in ran5&)1- l&n)#)- 3) 4rint)i)

for loops o#er indices


range
Jere is the top part o# the help #or ran5&,
%la## ran5&)o'I&%t) T ran5&)8#tart-K #to48- #t&4K) -> ran5& o'I&%t T T F&t6rn# a !irt6al #&J6&n%& of n6*'&r# fro* #tart to #to4 'y #t&4.

)he #to4 $alue is not included% ran5& is t picall used in a for loop to iterate o$er a se6uence o# numbers% Jere are some examples,
S @t&rat& o!&r t1& n6*'&r# 0- 1- 2- 3- an" 4. for i in ran5&)5)

S @t&rat& o!&r t1& n6*'&r# 2- 3- an" 4. for i in ran5&)2- 5)

S @t&rat& o!&r t1& n6*'&r# 3- 6- 9- 12- 15- an" 18. for i in ran5&)3- 20- 3)

)terating o#er the indices o" a list


>ecause l&n returns the number o# items in a list. it can be used "ith ran5& to iterate o$er all the

indices% )his loop prints all the $alues in a list,


for i in ran5&)l&n)l#t)) 4rint)l#t8iK)

)his also gi$es us #lexibilit to process onl part o# a list% -or example. /e can print onl the #irst hal# o# the list,
for i in ran5&)l&n)l#t) // 2) 4rint)l#t8iK)

Or e$er other element,


for i in ran5&)0- l&n)l#t)- 2) 4rint)l#t8iK)

0ot $3hat$ but $3here$


*re$iousl . "e ha$e "ritten loops o$er characters in a string or items in a list% Jo"e$er. sometimes there are problems "here 5no"ing the $alue o# the items in a list or the characters in a string is not enoughK "e need to 5no" "here it occurs &i%e% its index'%

Example 6
)he #irst example is described belo",
"&f %o6nt2a"Ia%&nt2r&4&at#)#) 999 )#tr) -> int F&t6rn t1& n6*'&r of o%%6rr&n%&# of a %1ara%t&r an" an a"Ia%&nt %1ara%t&r '&in5 t1& #a*&. >>> %o6nt2a"Ia%&nt2r&4&at#)9a'%%"&ff5519) 3 999 r&4&at# 3 0 for i in ran5&)l&n)#) - 1) if #8iK 33 #8i + 1K r&4&at# 3 r&4&at# + 1 r&t6rn r&4&at#

/e "ant to compare a character in the string "ith another character in the string beside it% )his is "h "e iterate o$er the indices because the location is important. and onl 5no"ing the $alue o# the character does not pro$ide us "ith enough in#ormation% )his is ho" "e are able to count repeated characters in a string% /e can+t execute the bod o# the loop i# i is l&n)#) - 1 because "e compare to #8i + 1K. and that "ould produce an @n"&xError%

Example 7
)he second example is described belo",
"&f #1ift2l&ft)B) 999 )li#t) -> Don&$y4&

S1ift &a%1 it&* in B on& 4o#ition to t1& l&ft an" #1ift t1& fir#t it&* to t1& la#t 4o#ition. >r&%on"ition l&n)B) >3 1

>>> #1ift2l&ft)89a9- 9'9- 9%9- 9"9K) 999 fir#t2it&* 3 B80K for i in ran5&)l&n)B) - 1) B8iK 3 B8i + 1K B8-1K 3 fir#t2it&*

-or the same reasons as abo$e. merel 5no"ing the $alue o# the items in the list is not enough since "e need to 5no" "here the items are locatedK "e need to 5no" the index &position' o# the item in the list%

Parallel 'ists and Strings


Correspondings Elements
)"o lists are parallel i# the ha$e the same length and the items at each index are someho" related% )he items at the same index are said to be at corresponding positions% ;onsider these t"o lists,
li#t1 3 81- 2- 3K li#t2 3 82- 4- 2K

<n these t"o lists. the corresponding element o# li#t180K is li#t280K. the corresponding element o# li#t281K is li#t181K. and so on%

Example o" Corresponding Elements


"&f *at%12%1ara%t&r#)#1- #2) 999 )#tr- #tr) -> int F&t6rn t1& n6*'&r of %1ara%t&r# in #1 t1at ar& t1& #a*& a# t1& %1ara%t&r at t1& %orr&#4on"in5 4o#ition of #2. >r&%on"ition l&n)#1) 33 l&n)#2)

>>> *at%12%1ara%t&r#)9at&9- 9a4&9) 2 >>> *at%12%1ara%t&r#)91&a"9- 91ar"9) 2 999 n6*2*at%1&# 3 0 for i in ran5&)l&n)#1)) if #18iK 33 #28iK n6*2*at%1&# 3 n6*2*at%1&# + 1

r&t6rn n6*2*at%1&#

)he #unction abo$e counts the corresponding elements o# the t"o strings that are the same character% <# a character o# #1 at index i is the same as the character o# #2 at the same index. then "e increment n6*2*at%1&# b 1 &since the match'% Other"ise. "e continue on to the next pair o# corresponding elements and compare them%

0ested 'ists
@ists can contain items o# an t pe. including other lists% )hese are called nested lists% Jere is an example%
>>> 5ra"&# 3 889:##i5n*&nt 19- 80K- 89:##i5n*&nt 29- 90K- 89:##i5n*&nt 39- 70KK >>> 5ra"&#80K 89:##i5n*&nt 19- 80K >>> 5ra"&#81K 89:##i5n*&nt 29- 90K >>> 5ra"&#82K 89:##i5n*&nt 39- 70K

)o access a nested item. #irst select the sublist. and then treat the result as a regular list% -or example. to access 9:##i5n*&nt 19. "e can #irst get the sublist and then use it as "e "ould a regular list,
>>> #6'li#t 3 5ra"&#80K >>> #6'li#t 89:##i5n*&nt 19- 80K >>> #6'li#t80K 9:##i5n*&nt 19 >>> #6'li#t81K 80

>oth #6'li#t and 5ra"&#80K contain the memor address o# the 89:##i5n*&nt 19- 80K nested list% /e can access the items inside the nested lists li5e this,
>>> 5ra"&#80K80K 9:##i5n*&nt 19 >>> 5ra"&#80K81K 80 >>> 5ra"&#81K80K 9:##i5n*&nt 29 >>> 5ra"&#81K81K 90 >>> 5ra"&#82K80K 9:##i5n*&nt 39 >>> 5ra"&#82K81K 70

0ested 'oops
Bodies o" 'oops
)he bodies o# loops can contain an statements. including other loops% /hen this occurs. this is 5no"n as a nested loop% Jere is a nested loop in$ol$ing 2 for loops,
for i in ran5&)10- 13) for I in ran5&)1- 5) 4rint)i- I)

Jere is the output,


10 10 10 10 11 11 11 11 12 12 12 12 1 2 3 4 1 2 3 4 1 2 3 4

:otice that "hen i is 1!. the inner loop executes in its entiret . and onl a#ter I has ranged #rom 1 through 4 is i assigned the $alue 11%

Example o" 0ested 'oops


"&f %al%6lat&2a!&ra5&#)5ra"&#) 999 )li#t of li#t of n6*'&r) -> li#t of float F&t6rn a n&E li#t in E1i%1 &a%1 it&* i# t1& a!&ra5& of t1& 5ra"&# in t1& inn&r li#t at t1& %orr&#4on"in5 4o#ition of 5ra"&#. >>> %al%6lat&2a!&ra5&#)8870- 75- 80K- 870- 80- 90- 100K- 880- 100KK) 875.0- 85.0- 90.0K 999 a!&ra5&# 3 8K S Pal%6lat& t1& a!&ra5& of &a%1 #6'li#t an" a44&n" it to a!&ra5&#. for 5ra"&#2li#t in 5ra"&# S Pal%6lat& t1& a!&ra5& of 5ra"&#2li#t. total 3 0 for *ar( in 5ra"&#2li#t total 3 total + *ar( a!&ra5&#.a44&n")total / l&n)5ra"&#2li#t))

r&t6rn a!&ra5&#

<n %al%6lat&2a!&ra5&#. the outer for loop iterates through each sublist in 5ra"&#% /e then calculate the a$erage o# that sublist using a nested. or inner. loop. and add the a$erage to the accumulator &the ne" list. a!&ra5&#'%

+eading iles
<n#ormation stored in #iles can be accessed b a * thon program% )o get access to the contents o# a #ile. ou need to open the #ile in our program% /hen ou are done using a #ile. ou should close it%

Opening and Closing A ile


* thon has a built-in #unction o4&n that can open a #ile #or reading% )he #orm o# o4&n is o4&n)fil&na*&- *o"&). "here mode is 9r9 &to open #or reading'. 9E9 &to open #or "riting'. or 9a9 &to open #or appending to "hat is alread in the #ile'% )his opens a #ile called @n +lan"&r# +i&l"#.txt #or reading,
flan"&r#2fil& 3 o4&n)9@n +lan"&r# +i&l"#.txt9- 9r9)

:ote that i# the #ile is sa$ed in the same director as our program. ou can simpl "rite the name o# the #ile. as "hat "as done in the abo$e example% Jo"e$er. i# it is not sa$ed in the same director . ou must pro$ide the path to it% )o close a #ile. ou "rite flan"&r#2fil&.%lo#&)) % )here are #our standard "a s to read #rom a #ile% 9ome use these methods, r&a"lin&)), read and return the next line #rom the #ile. including the ne"line character &i# it exists'% Return the empt string i# there are no more lines in the #ile% r&a"lin&#)), read and return all lines in a #ile in a list% )he lines include the ne"line character% r&a")), read the "hole #ile as a single string% Approach )he r&a"lin& approach Code
fil& 3 o4&n)fil&na*&- 9r9) S F&a" lin&# 6ntil E& r&a%1 t1& S 4la%& in t1& fil& t1at E& Eant. lin& 3 fil&.r&a"lin&)) E1il& we are not at the place we want lin& 3 fil&.r&a"lin&)) S DoE E& 1a!& r&a%1&" t1& #&%tion S of t1& fil& E& Eant to 4ro%&##. lin& 3 fil&.r&a"lin&)) E1il& we are not at the end of the section process the line lin& 3 fil&.r&a"lin&))

3hen to use it /hen ou "ant to process onl part o# a #ile%

flan"&r#2fil&.%lo#&)) fil& 3 o4&n)fil&na*&- 9r9)

)he for line in "ile approach

for lin& in fil& process the line fil&.%lo#&)) fil& 3 o4&n)fil&na*&- 9r9)

/hen ou "ant to process e$er line in the #ile one at a time%

)he r&a" approach

%ont&nt# 3 fil&.r&a")) now process %ont&nt# fil&.%lo#&)) fil& 3 o4&n)fil&na*&- 9r9) S ?&t t1& %ont&nt# a# a li#t of #trin5#. %ont&nt#2li#t 3 fil&.r&a"lin&#)) process %ont&nt#2li#t using indexing to access particular lines from the file fil&.%lo#&))

/hen ou "ant to read the "hole #ile at once and use it as a single string%

)he r&a"lin&# approach

/hen ou "ant to examine each line o# a #ile b index%

Examples "rom the #ideo


Jere are the code examples that appeared in the $ideo% (ll o# them read the entire #ile into a string and print that string% The readline approach
flan"&r#2fil& 3 o4&n)flan"&r#2fil&na*&- 9r9) flan"&r#24o&* 3 99 lin& 3 flan"&r#2fil&.r&a"lin&)) E1il& lin& Q3 ,, flan"&r#24o&* 3 flan"&r#24o&* + lin& lin& 3 flan"&r#2fil&.r&a"lin&)) 4rint)flan"&r#24o&*) flan"&r#2fil&.%lo#&))

The for line in file approach


flan"&r#2fil& 3 o4&n)flan"&r#2fil&na*&- 9r9) flan"&r#24o&* 3 99 for lin& in flan"&r#2fil& flan"&r#24o&* 3 flan"&r#24o&* + lin& 4rint)flan"&r#24o&*) flan"&r#2fil&.%lo#&))

The read approach


flan"&r#2fil& 3 o4&n)flan"&r#2fil&na*&- 9r9) flan"&r#24o&* 3 flan"&r#2fil&.r&a")) 4rint)flan"&r#24o&*) flan"&r#2fil&.%lo#&))

The readlines approach


flan"&r#2fil& 3 o4&n)flan"&r#2fil&na*&- 9r9) flan"&r#24o&* 3 99 flan"&r#2li#t 3 flan"&r#2fil&.r&a"lin&#)) for lin& in flan"&r#2li#t flan"&r#24o&* 3 flan"&r#24o&* + lin& 4rint)flan"&r#24o&*) flan"&r#2fil&.%lo#&))

3rite iles
3riting To A ile 3ithin A Python Program
<n order to "rite to a #ile. "e use "ile.Erit&)#tr)% )his method "rites a string to a #ile% Bethod Erit& "or5s li5e * thon+s 4rint #unction. except that it does not add a ne"line character%

ile dialogs
Bodule t(int&r has a submodule called fil&"ialo5% /e import it li5e this,
i*4ort t(int&r.fil&"ialo5

-unction a#(o4&nfil&na*& as5s the user to select a #ile to open,


t(int&r.fil&"ialo5.a#(o4&nfil&na*&))

)his #unction returns the #ull path to the #ile. so "e can use that "hen "e call #unction o4&n to open that #ile%
fro*2fil&na*& 3 t(int&r.fil&"ialo5.a#(o4&nfil&na*&))

-unction a#(#a!&a#fil&na*& as5s the user to select a #ile to sa$e to. and pro$ides a "arning i# the #ile alread exists%
to2fil&na*& 3 t(int&r.fil&"ialo5.a#(#a!&a#fil&na*&))

Example
>elo" is a program that copies a #ile. but puts ,Po4y, as the #irst line o# the copied #ile% <n order to prompt a user #or a #ile%

:o" "e can open the #ile "e "ant to read #rom and get the contents,
fro*2fil& 3 o4&n)fro*2fil&na*&- 9r9) %ont&nt# 3 fro*2fil&.r&a")) fro*2fil&.%lo#&))

(nd "e can open the #ile "e "ant to "rite to and "rite the contents,
to2fil& 3 o4&n)to2fil&na*&- 9E9) to2fil&.Erit&)9Po4yNn9) S <& 1a!& to a"" t1& n&Elin& o6r#&l!&#. to2fil&.Erit&)%ont&nt#) S DoE Erit& t1& %ont&nt# of t1& fil&. to2fil&.%lo#&))

Tuples
)mmutable Se(uences
)uples are immutable se6uences, the cannot be modi#ied% )uples and lists ha$e much in common. but lists are mutable se6uences, the can be modi#ied% )uples use parentheses instead o# s6uare brac5ets,
l#t 3 89a9- 3- -0.2K t64 3 )9a9- 3- -0.2)

Once created. items in lists and tuples are accessed using the same notation,
>>> l#t80K 9a9 >>> t6480K 9a9

9licing can be used "ith both,


>>> l#t8 2K 89a9- 3K >>> t648 2K )9a9- 3)

)uples cannot be modi#ied,


>>> t6480K 3 9'9 $y4&Error 9t64l&9 o'I&%t "o&# not #644ort it&* a##i5n*&nt

)uples ha$e #e"er methods than lists% <n #act. the onl regular methods are %o6nt and in"&x,
>>> "ir)li#t) 8922a""229- 922%la##229- 922%ontain#229- 922"&lattr229- 922"&lit&*229- 922"o%229922&J229- 922for*at2299225&229- 9225&tattri'6t&229- 9225&tit&*229- 9225t229- 9221a#1229- 922ia""229922i*6l229- 922init229922it&r229- 922l&229- 922l&n229- 922lt229- 922*6l229- 922n&229- 922n&E229922r&"6%&229- 922r&"6%&2&x229922r&4r229- 922r&!&r#&"229- 922r*6l229- 922#&tattr229- 922#&tit&*229922#i0&of229- 922#tr229-

922#6'%la##1oo(229- 9append', 'count', extend', 'index', 'insert', 'pop', 'remo e', 're erse', sort'K >>> "ir)t64l&) 8922a""229- 922%la##229- 922%ontain#229- 922"&lattr229- 922"o%229- 922&J229922for*at229- 9225&2299225&tattri'6t&229- 9225&tit&*229- 9225&tn&Ear5#229- 9225t229- 9221a#1229922init229- 922it&r229922l&229- 922l&n229- 922lt229- 922*6l229- 922n&229- 922n&E229- 922r&"6%&229922r&"6%&2&x229922r&4r229- 922r*6l229- 922#&tattr229- 922#i0&of229- 922#tr229922#6'%la##1oo(229- 'count', 'index'K

)he rest o# the list methods are not a$ailable #or tuple because the modi# the obEect. and tuples. being immutable. cannot be modi#ied% ( for can be used to iterate o$er the $alues in a tuple,
>>> t64 3 )9a9- 3- -0.2) >>> for it&* in t64 4rint)it&*) a 3 -0.2

( tuple can be passed as an argument to the built-in #unction l&n,


>>> l&n)t64) 3

<t is also possible to iterate o$er the indices o# a tuple,


>>> for i in ran5&)l&n)t64)) 4rint)t648iK) a 3 -0.2

Type dict
!ictionary
(nother "a to store collections o# data is using * thon+s dictionar t pe, "i%t% )he general #orm o# a dictionar is,
U(&y1 !al6&1- (&y2 !al6&2- ...- (&yD !al6&DV

Le s must be uni6ue% 8alues ma be duplicated% -or example,


a#n2to25ra"& 3 U9:19 80- 9:29 90- 9:39 90V

<n the example abo$e. the 5e s are uni6ue, 9:19. 9:29 and 9:39% )he $alues are not uni6ue, 80. 90 and 90%

,o- To Modi"y !ictionaries


?ictionaries are mutable, the can be modi#ied% )here are a series o# operations and methods ou can appl to dictionaries "hich are outlined belo"% Operation o'I&%t in "i%t ?escription ;hec5s "hether o'I&%t is a 5e in "i%t% Returns the number o# 5e s in "i%t% Remo$es a 5e and its associated $alue #rom "i%t% <# (&y does not exist in "i%t. adds (&y and its associated !al6& to "i%t% <# (&y exists in "i%t. updates "i%t b setting the $alue associated "ith (&y to !al6&% Example
>>> a#n2to25ra"& 3 U9:19 >>> 9:19 in a#n2to25ra"& $r6& >>> 80 in a#n2to25ra"& +al#& >>> a#n2to25ra"& 3 U9:19 >>> l&n)a#n2to25ra"&) 3 80- 9:29 90- 9:39 90V

l&n)"i% t) "&l "i%t8(& yK

80- 9:29

90- 9:39

90V

>>> a#n2to25ra"& 3 U9:19 80- 9:29 >>> "&l a#n2to25ra"&89:19K >>> a#n2to25ra"& U9:39 90- 9:29 90V

90- 9:39

90V

"i%t8(& yK 3 !al6&

>>> a#n2to25ra"& 3 U9:19 80- 9:29 90V >>> a#n2to25ra"&89:49K 3 70 >>> a#n2to25ra"& U9:19 80- 9:39 90- 9:29 90- 9:49

90- 9:39

70V

Accessing )n"ormation rom !ictionaries


?ictionaries are unordered% )hat is. the order the 5e -$alue pairs are added to the dictionar has no e##ect on the order in "hich the are accessed% -or example,
>>> a#n2to25ra"& 3 U9:19 80- 9:29 >>> for a##i5n*&nt in a#n2to25ra"& 4rint)a##i5n*&nt) :1 :3 :2 70- 9:39 90V

)he #or-loop abo$e printed out the 5e s o# the dictionar % <t is also possible to print out the $alues,
>>> a#n2to25ra"& 3 U9:19 80- 9:29 70- 9:39 >>> for a##i5n*&nt in a#n2to25ra"& 4rint)a#n2to25ra"&8a##i5n*&ntK) 90V

80 90 70

-inall . both the 5e s are $alues can be printed,


>>> a#n2to25ra"& 3 U9:19 80- 9:29 70- 9:39 90V >>> for a##i5n*&nt in a#n2to25ra"& 4rint)a##i5n*&nt- a#n2to25ra"&8a##i5n*&ntK) :1 80 :3 90 :2 70

Empty !ictionaries
( dictionar can be empt % -or example,
" 3 UV

,eterogeneous !ictionaries
( dictionar can ha$e 5e s o# di##erent t pes% -or example. one 5e can be o# t pe int and another o# t pe #tr,
" 3 U9a44l&9 1- 3 4V

)mmutable 8eys
)he 5e s o# a dictionar must be immutable% )here#ore. lists. dictionar and other mutable t pes cannot be used as 5e s% )he #ollo"ing results in an error,
"881- 2KK 3 9'anana9

9ince lists are mutable. the cannot be 5e s% <nstead. to use a se6uence as a 5e . t pe t64l& can be used,
"8)1- 2)K 3 9'anana9

)n#erting a !ictionary
S-itching 8eys and Values
?ictionaries ha$e 5e s that are uni6ue and each 5e has a $alue associated "ith it% -or example. here is a dictionar mapping #ruit to their colours,
fr6it2to2%olo6r 3 U9Eat&r*&lon9 95r&&n9- 94o*&5ranat&9 9r&"994&a%19 9oran5&9- 9%1&rry9 9r&"9- 94&ar9 95r&&n99'anana9 9y&lloE9- 94l6*9 946r4l&9- 9oran5&9 9oran5&9V

)o in$ert the dictionar . that is. s"itch the mapping to be colours to #ruit. here is one approach,
>>> %olo6r2to2fr6it 3 UV >>> for fr6it in fr6it2to2%olo6r %olo6r 3 fr6it2to2%olo6r8fr6itK %olo6r2to2fr6it8%olo6rK 3 fr6it

>>> %olo6r2to2fr6it U9oran5&9 9oran5&9- 946r4l&9 94o*&5ranat&9V

94l6*9- 95r&&n9

94&ar9- 9y&lloE9

9'anana9- 9r&"9

)he resulting dictionar is missing some #ruit% )his happens since colours. "hich are 5e s. are uni6ue so later assignments using the same colour replace earlier entries% ( "a to remed this is to map colours to a list o# #ruit%

Mapping A 8ey To A 'ist


-or the example abo$e. "e need to consider t"o cases "hen adding a colour and a #ruit to the dictionar , 1% <# the colour is not a 5e in the dictionar . add it "ith its $alue being a single element a list consisting o# the #ruit% 2% <# the colour is alread a 5e . append the #ruit to the list o# #ruit associated "ith that 5e %
>>> %olo6r2to2fr6it 3 UV >>> for fr6it in fr6it2to2%olo6r S <1at %olo6r i# t1& fr6itM %olo6r 3 fr6it2to2%olo6r8fr6itK if not )%olo6r in %olo6r2to2fr6it) %olo6r2to2fr6it8%olo6rK 3 8fr6itK &l#& %olo6r2to2fr6it8%olo6rK.a44&n")fr6it) >>> %olo6r2to2fr6it U9oran5&9 894&a%19- 9oran5&9K- 946r4l&9 894l6*9K- 95r&&n9 89Eat&r*&lon994&ar9K- 9y&lloE9 89'anana9K- 9r&"9 89%1&rry9- 94o*&5ranat&9KV

You might also like