Python Basics
Python Basics
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
lo"est
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
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
)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
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%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#).
!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 >>> rlt 3 ar&a)10- 7.45) >>> rlt 37.25
<# 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%
<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&
/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
/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,.,)
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&#.
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
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
'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&
+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%
*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))
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
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*&
-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
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)
>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)
/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#&
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
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
)he #irst character o# the string is at index ! and can be accessed using this brac5et notation,
>>> #80K 9B9
: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
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
<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%
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#tart#Eit19- 9#tri49- 9#Ea4%a#&9- 9titl&99tran#lat&9- 9644&r990fill9K
-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)
)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
)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 #%
>>> %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%
<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
'ist Operations
@i5e strings. lists can be indexed,
>>> 5ra"PK 80 >>> 5ra"QK 90 >>> 5ra"RK 70
@ists can also be sliced. using the same notation as #or strings,
>>> 5ra"P 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#&
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'%
@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
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)
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#&) )
9ort the list #rom smallest to largest% <nsert obEect at the gi$en index. mo$ing items to ma5e room%
li#t.%o6nt )o'I&%t)
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
>>> %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##QK 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)
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)
)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# 3- 6- 9- 12- 15- an" 18. for i in ran5&)3- 20- 3)
)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)
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%
<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%
>>> *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"PK 89:##i5n*&nt 19- 80K >>> 5ra"QK 89:##i5n*&nt 29- 90K >>> 5ra"RK 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"PK >>> #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"PK 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"PK80K 9:##i5n*&nt 19 >>> 5ra"PK81K 80 >>> 5ra"QK80K 9:##i5n*&nt 29 >>> 5ra"QK81K 90 >>> 5ra"RK80K 9:##i5n*&nt 39 >>> 5ra"RK81K 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)
: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%
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%
: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&))
for lin& in fil& process the line fil&.%lo#&)) fil& 3 o4&n)fil&na*&- 9r9)
%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%
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
)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
)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
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
<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%
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
)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
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
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%