1 An introduction to Python for absolute beginners
2 Sources ● An introduction to Python for absolute beginners Bob Dowling University Information Services scientific-computing@ucs.cam.ac.uk http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB ● Introduction to Python Chen Lin clin@brandeis.edu ● Learn Python the hard way http://learnpythonthehardway.org/book/ ● http://python.org/
3 Advices ● Go through each exercise. ● Type in each sample exactly. ● Make it run. ● Reading and Writing ● Attention to Detail ● Spotting Differences ● Do Not Copy-Paste ● A Note on Practice and Persistence
4 Course outline ― 1 Who uses Python & what for What sort of language it is How to launch Python Python scripts Reading in user data Numbers Conversions Comparisons Names for values Text and Comments Truth & Falsehood
5 Course outline ― 2 Assignment Names Our first “real” program Loops if… else… Indentation
6 Course outline ― 3 Lists Indices Lengths Changing items Extending lists Methods Creating lists Testing lists Removing from lists for… loop Iterables Slices
7 Course outline ― 4 Files Reading & writing Writing our own functions Tuples Modules System modules External modules Dictionaries Formatted text
8 What is Python ● Cross platform ● Multi-purpose (Web, GUI, Scripting, …) ● Object Oriented ● Interpreted ● Stringly typed ● Dynamically typed ● Focus on readability and productivity ● Powerful
9 Features ● Everything is an Object ● Interactive shell ● IDE ● Huge ecosystem
10 History ● Created in 1989 by Guido Van Rossum ● 1994 – Python 1.0 ● 2000 – Python 2.0 ● 2008 – Python 3.0
11 Who uses Python? On-line games Web services Applications Science Instrument control Embedded systems en.wikipedia.org/wiki/List_of_Python_software
12 What sort of language is Python? Explicitly compiled to machine code Purely interpreted C, C++, Fortran Shell, Perl Explicitly compiled to byte code Java, C# Implicitly compiled to byte code Python Compiled Interpreted
Major versions of Python ● “Python” or “CPython” is written in C/C++ – Version 2.7 came out in mid-2010 – Version 3.1.2 came out in early 2010 – Latest stable version is 3.5.1 of 3.x series ● “Jython” is written in Java for the JVM ● “IronPython” is written in C# for the .Net environment ● PyPy Go To Website
Downloading Python ● https://www.python.org/downloads – 3.5.1 ● Download Windows x86-64 executable installer – 2.7.11 ● Download Windows x86-64 MSI installer
15 Running Python ― 1
16 Running Python ― 1.5
17 Running Python ― 2 $ python3 Unix prompt Unix command Introductory blurb Python prompt [GCC 4.6.3] on linux2 (default, May 3 2012, 15:54:42) Python version Python 3.2.3 >>>
18 Quitting Python >>> exit() >>> quit() >>> Ctrl D+ Any one of these
19 PEP 8 ● Python Enhancement Proposals (PEP) – https://www.python.org/dev/peps/ ● PEP 8 – Style Guide for Python Code – https://www.python.org/dev/peps/pep-0008/
20 A first Python command >>> print('Hello, world!') Hello, world! >>> Python prompt Python command Output Python prompt
21 Python commands print Python “function” ( Function’s “argument” Round brackets ― “parentheses” ( )'Hello, world!' “Case sensitive”print PRINT≠
22 Python text The body of the text Quotation marks ' 'Hello, world! ! The quotes are not part of the text itself.
23 Python comments ● Notes, examples in a single or multiple lines ● Single line: # print('Hello, world!') ● Multiple lines: ''' You can writhe anything here: print('Hello, world!') Same in English '''
24 Quotes? print Command 'print' Text
25 Alternative Pythons iPython idle
26 Python scripts hello1.py File in home directory $ python3 Hello, world! $ Unix prompt Unix command to run Python Python script Python script’s output Unix prompt hello1.py print('Hello, world!') Run from Unix prompt
27 Editing Python scripts — 1
28 Editing Python scripts — 2
Development Environments what IDE to use? http://stackoverflow.com/questions/81584 1. PyDev with Eclipse 2. Komodo 3. Emacs 4. Vim 5. TextMate 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows) 10.BlueFish (Linux)
30 PyCharm
31 PyCharm ● Download – https://www.jetbrains.com/pycharm/download/ – Community version
32 Progress Interactive Python Python scripts print() command Simple Python text
33 Exercise 1 1. Print “Rock and roll” from interactive Python. 2. Edit exercise1.py to print the same text. 3. Run the modified exercise1.py script. 2 minutes ❢ Please ask if you have questions.
34 A little more text hello2.py print(' эłℏ Ꮣዐ, ω☺ ∂‼')ⲗրFull “Unicode” support www.unicode.org/charts/
35 Getting characters ğ AltGr Shift+ #+ g “LATIN SMALL LETTER G WITH BREVE” u011f Character Selector Linux ˘
36 Text: a “string” of characters >>> type('Hello, world!') <class 'str'> A string of characters H e l l o , ␣ w o r l d !13 Class: string Length: 13 Letters str
37 Text: “behind the scenes” str 13 72 101 108 108 111 44 32 33100… 011f16 ğ >>> chr(287) 'ğ' >>> ord('ğ') 287 >>> 'u011f' 'ğ' 28710
38 Adding strings together: + print('Hello, ' + 'world!') hello3.py “Concatenation” >>> 'Hello, ' + 'world!' 'Hello, world!' >>>
39 Pure concatenation >>> 'Hello,␣' + 'world!' 'Hello, world!' >>> 'Hello,' + '␣world!' 'Hello, world!' >>> 'Hello,' + 'world!' 'Hello,world!' Only simple concatenation No spaces added automatically.
40 Single & double quotes >>> 'Hello, world!' 'Hello, world!' >>> 'Hello, world!' Single quotes "Hello, world!" Double quotes Single quotes Single quotes
41 Python strings: input & output 'Hello, world!' 'Hello, world!' "Hello, world!" Single or double quotes on input. Single quotes on output. Create same string object. H e l l o , ␣ w o r l d !13str
42 Uses of single & double quotes >>> He said "hello" to her. print('He said "hello" to her.') >>> He said 'hello' to her. print("He said 'hello' to her.")
43 Why we need different quotes >>> File "<stdin>", line 1 print('He said 'hello' to her.') ^ SyntaxError: invalid syntax print('He said 'hello' to her.') ✘
44 Adding arbitrary quotes >>> print('He said 'hello' to her.') He said 'hello' to her. ' " ' " “Escaping” Just an ordinary character. H e s a i␣ ' h e l l23str o ' t o h e r .d ␣␣ ␣
45 Putting line breaks in text >>> print('Hello, Hello, world! What we want world') ↵ Try this >>> print('Hello, ↵ File "<stdin>", line 1 print('Hello, ^ >>> SyntaxError: EOL while scanning string literal “EOL”: End Of Line ✘
46 Inserting “special” characters >>> print('Hello, Hello, world! world!')n Treated as a new line. str 13 e l l o , ↵ w o r l d !H n Converted into a single character. >>> len 13 len() function: gives the length of the object ('Hello,nworld!')
47 The backslash ' " ' " Special Ordinary n t ↵ ⇥ Ordinary Special
48 n: unwieldy for long text 'SQUIRE TRELAWNEY, Dr. Livesey, and then rest of these gentlemen having asked men to write down the whole particularsnabou t Treasure Island, from thenbeginning to the end, keeping nothingnback but the b earings of the island,nand that only bec ause there is stillntreasure not yet lif ted, I take up mynpen in the year of gra ce 17__ and gonback to the time when my father keptnthe Admiral Benbow inn and t he brownnold seaman with the sabre cut f irstntook up his lodging under our roof.' Single line
49 Special input method for long text Triple quotes ''' rest of these gentlemen having asked me to write down the whole particulars about Treasure Island, from the beginning to the end, keeping nothing back but the bearings of the island, and that only because there is still treasure not yet lifted, I take up my pen in the year of grace 17__ and go back to the time when my father kept the Admiral Benbow inn and the brown old seaman with the sabre cut first took up his lodging under our roof. SQUIRE TRELAWNEY, Dr. Livesey, and the ''' Multiple lines
50 Python’s “secondary” prompt >>> '''Hello, world'''... Python asking for more of the same command.
51 It’s still just text! >>> 'Hello,nworld!' 'Hello >>> ... '''Hello, world!''' 'Hellonworld' world'n Python uses n to represent line breaks in strings. Exactly the same!
52 Your choice of input quotes: 'Hello,nworld!' "Hello,nworld!" """Hello, world!""" '''Hello, world!''' str 13 e l l o , ↵ w o r l d !H Same result: Four inputs:
53 Progress International text print() Concatenation of strings Long strings Special characters
54 Exercise 2 3 minutes 1. Replace XXXX in exercise2.py so it prints the following text (with the line breaks) and then run the script. coffee Kaffee café caffè é è u00e8 u00e9 AltGr AltGr + + # ; e e
55 Attaching names to values message = 'Hello, world!' print(message) hello3.py str 13 e l l o , ␣ w o r l d !Hmessage “variables” >>> message='Hello, world!' >>> message 'Hello, world!' >>> type(message) <class 'str'>
56 Attaching names to values message = 'Hello, world!' print(message) hello4.py print function str 13 e l l o , ␣ w o r l d !Hmessage >>> type(print) <class 'builtin_function_or_method'>
57 Reading some text into a script $ python3 Yes? input1.py Boo! Boo! message = input('Yes?␣') print(message) input1.py input('Yes?␣') message = … print(message)
58 Can't read numbers directly! number = input('N?␣') print(number + 1) input2.py $ python3 input2.py N? 10 Traceback (most recent call last): File "input2.py", line 2, in <module> print( + ) string integer number TypeError: Can't convert 'int' object to str implicitly ✘ 1
59 input(): strings only number = input('N?␣') print(number + 1) input2.py ✘$ python3 input2.py N? 10 input('N? ')␣ str 2 01 int 10≠
60 Some more types >>> type('Hello, world!') <class 'str'> >>> type(42) <class 'int'> >>> type(3.14159) <class 'float'> string of characters integer floating point number
61 Converting text to integers >>> int('10') 10 >>> int('␣-100␣') -100 >>> int('100-10') ValueError: invalid literal for int() with base 10: '100-10' str 2 01 int 10 str 6 -␣ int -100 01 ␣0 ✘
62 Converting text to floats >>> float('10.0') 10.0 >>> float('␣10.␣') 10.0 '10.0' is a string 10.0 is a floating point number
63 Converting between ints and floats >>> float(10) 10.0 >>> int(10.9) 10 Truncates fractional part >>> int(-10.9) -10
64 Converting into text >>> str(10) '10' >>> str(10.000) '10.0' integer float string string
65 Converting between types int() float() anything anything integer float str() anything string Functions named after the type they convert into.
66 Reading numbers into a script text = input('N? ')␣ number = int(text) print(number + 1)$ N? 11 python3 input3.py 10
67 Stepping through our script — 1 text = input('N?␣') number = int(text) print(number + 1) str 3 ?N ␣
68 Stepping through our script — 2 text = input('N?␣') number = int(text) print(number + 1) str 3 ?N ␣ input function str 2 01 NB: text, not number
69 Stepping through our script — 3 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text
70 Stepping through our script — 4 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text int function int 10
71 Stepping through our script — 5 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text int function int 10number
72 Stepping through our script — 6 text = input('N? ')␣ number = int(text) print(number + 1) int 10number
73 Stepping through our script — 7 text = input('N? ')␣ number = int(text) print(number + 1) int 10number function int 11 + int 1
74 Stepping through our script — 6 text = input('N? ')␣ number = int(text) print(number + 1) int 10number int 11 functionprint
75 Progress Names Types Type conversions Values Reading in text str() int() float() input(prompt) name = value strings integers floating point numbers
76 Exercise 3 Replace the two XXXX in exercise3.py to do the following: 1. Prompt the user with the text “How much?␣”. 2. Convert the user’s answer to a floating point number. 3. Print 2.5 plus that number. 3 minutes
77 Integers ℤ{… -2, -1, 0, 1, 2, 3, 4 …}
78 Integer addition & subtraction >>> 20+5 25 >>> 20␣-␣5 15 Spaces around the operator don’t matter. “No surprises”
79 Integer multiplication There is no “×” on the keyboard. Linux: ,+ShiftAltGr + Use “*” instead >>> 20␣*␣5 100 Still no surprises
80 Integer division There is no “÷” on the keyboard. Linux: .+ShiftAltGr + Use “/” instead >>> 20␣/␣5 4.0 This is a floating point number! Surprise!
81 Integer division gives floats ! Fractions >>> 20␣/␣40 0.5 >>> 20␣/␣30 0.6666666666666666 Floats sometimes Consistency Floats always !
82 Integer division gives floats ! >>> 20␣//␣4 5 ! // Special operation to stick with integers >>> 21␣//␣4 5 >>> -21␣//␣4 -6 >>> 20␣/␣4 5.0 >>> 21␣/␣4 5.25 >>> -21␣/␣4 -5.25
83 Integer powers There is no “42 ” on the keyboard. Use “**” instead >>> 4␣**␣2 16 >>> 4*␣*2 SyntaxError: invalid syntax Spaces around the operator don’t matter. Spaces in the operator do!
84 Integer remainders e.g. Is a number even or odd? >>> 4␣%␣2 0 >>> 5␣%␣2 1 Use “%” >>> -5␣%␣2 1 Remainder is always non-negative
85 How big can a Python integer be? >>> 2**2 4 >>> 4**2 16 >>> 16**2 256 >>> 256**2 65536 >>> 65536**2 4294967296 >>> 256**2 65536 >>> 256**2 65536 >>> 2**2 4
86 How big can a Python integer be? >>> 4294967296**2 18446744073709551616 >>> 18446744073709551616**2 340282366920938463463374607431768211456 >>> 340282366920938463463374607431768211456**2 1157920892373161954235709850086879078532699846 65640564039457584007913129639936 >>> 115792089237316195423570985008687907853269 1340780792994259709957402499820584612747936582 0592393377723561443721764030073546976801874298 1669034276900318581864860508537538828119465699 46433649006084096 984665640564039457584007913129639936**2
87 How big can a Python integer be? 10443888814131525066917527107166243825799642490473837803842334832839 53907971557456848826811934997558340890106714439262837987573438185793 60726323608785136527794595697654370999834036159013438371831442807001 18559462263763188393977127456723346843445866174968079087058037040712 84048740118609114467977783598029006686938976881787785946905630190260 94059957945343282346930302669644305902501597239986771421554169383555 98852914863182379144344967340878118726394964751001890413490084170616 75093668333850551032972088269550769983616369411933015213796825837188 09183365675122131849284636812555022599830041234478486259567449219461 70238065059132456108257318353800876086221028342701976982023131690176 78006675195485079921636419370285375124784014907159135459982790513399 61155179427110683113409058427288427979155484978295432353451706522326 90613949059876930021229633956877828789484406160074129456749198230505 71642377154816321380631045902916136926708342856440730447899971901781 46576347322385026725305989979599609079946920177462481771844986745565 92501783290704731194331655508075682218465717463732968849128195203174 57002440926616910874148385078411929804522981857338977648103126085903 00130241346718972667321649151113160292078173803343609024380470834040 3154190336 There is no limit! Except for machine memory
88 Big integers 2 4 16 256 65536 4294967296 18446744073709551616 3402823669209384634… 63374607431768211456 C / C++ Fortran Out of the reach of C or Fortran! long long INTEGER*16 long INTEGER*8 int INTEGER*4
89 Floating point numbers 1.0 0.33333333 3.14159265 2.71828182 ℝ✗
90 Basic operations >>> 20.0 + 5.0 25.0 >>> 20.0 - 5.0 15.0 >>> 20.0 * 5.0 100.0 >>> 20.0 / 5.0 4.0 >>> 20.0 ** 5.0 3200000.0 Equivalent to integer arithmetic
91 Floating point imprecision >>> 1.0 / 3.0 0.3333333333333333 >>> 10.0 / 3.0 3.3333333333333335 ≈ 17 significant figures If you are relying on this last decimal place, you are doing it wrong!
92 Hidden imprecision >>> 0.1 0.1 >>> 0.1 + 0.1 0.2 >>> 0.1 + 0.1 + 0.1 0.30000000000000004 Really: if you are relying on this last decimal place, you are doing it wrong! !
93 How big can a Python float be? ― 1 >>> 65536.0**2 4294967296.0 >>> 4294967296.0**2 1.8446744073709552e+19 So far, so good. Switch to “scientific notation” 1.8446744073709552 1.8446744073709552 ×1019 e+19
94 Floats are not exact >>> 4294967296**2 18446744073709551616 >>> 4294967296.0**2 1.8446744073709552e+19 Integer Floating point 1.8446744073709552×1019 18446744073709552000 18446744073709551616- 384
95 How big can a Python float be? ― 2 >>> 1.8446744073709552e+19**2 3.402823669209385e+38 >>> 3.402823669209385e+38**2 1.157920892373162e+77 >>> 1.157920892373162e+77**2 1.3407807929942597e+154 >>> 1.3407807929942597e+154**2 OverflowError: (34, 'Numerical result out of range') So far, so good. Too big!
96 Floating point limits 1.2345678901234567×10N 17 significant figures -325 < N < 308 4.94065645841×10-324 < N < 8.98846567431×10307 Positive values:
97 z z2 Complex numbers >>> (1.25+0.5j)**2 (1.3125+1.25j) ℂ ℜ ℑ
98 Progress Arithmetic Integers Floating point numbers Complex numbers + - * / ** % No limits! Limited size Limited precision
99 Exercise 4 3 minutes Replace the XXXX in exercise4.py to evaluate and print out the following calculations: 1. 223 ÷ 71 2. (1 + 1/100)100 3. (1 + 1/10000)10000 4. (1 + 1/1000000)1000000 Note: Brackets work in Python arithmetic just like they do in normal mathematics.
100 Comparisons 5 < 10 5 > 10 ✘✘✘ ✔ ✘✘✘✘✘✘
101 Comparisons >>> 5 < 10 True >>> 5 > 10 False Asking the question Asking the question ✘✘✘ ✔ ✘✘✘✘✘✘
102 True & False >>> type(True) <class 'bool'> “Booleans” 5 10+ 5 10< int int 15 True int bool
103 True & False bool ✓ bool ✗ True False Only two values
104 Six comparisons Maths = ≠ < > ≤ ≥ Python == != < > <= >= Double equals sign
105 Equality comparison & assignment name = value = value1 == value2 == Attach a name to a value. Compare two values
106 Textual comparisons >>> 'cat' < 'dog' True Alphabetic ordering >>> 'Cat' < 'cat' True >>> 'Dog' < 'cat' True Uppercase before lowercase All uppercase before lowercase
107 Ordering text is complicated German: Swedish: z < ö ö < z Python inequalities use Unicode character numbers. This is over-simplistic for “real” use. Alphabetical order? “Collation” is a whole field of computing in itself
108 “Syntactic sugar” 0 < number < 10 0 < number and number < 10 >>> number = 5 >>> 0 < number < 10 True
109 Converting to booleans float() Converts to floating point numbers int() Converts to integers str() Converts to strings bool() Converts to booleans <class 'float'> <class 'int'> <class 'str'> <class 'bool'>
110 Useful conversions 'Fred' True '' False Non-empty string Empty string 1 True 0 False Non-zero Zero 12 True -1 True
111 Boolean operations Numbers have +, –, * … What do booleans have? bool ✓ bool ✗ bool bool bool?
112 Boolean operations ― “and” bool bool booland True Trueand True Falseand False Trueand False Falseand True False False False Both have to be True
113 Boolean operations ― “and” >>> 4 < 5 and 6 < 7 True 4 < 5 6 < 7 True True and True >>> 4 < 5 and 6 > 7 False 4 < 5 6 > 7 True False and False
114 Boolean operations ― “or” bool bool boolor True Trueor True False False True False False True False True True At least one has to be Trueor or or
115 Boolean operations ― “or” >>> 4 < 5 or 6 < 7 True 4 < 5 6 < 7 True True or True >>> 4 < 5 or 6 > 7 True 4 < 5 6 > 7 True False or True
116 Boolean operations ― “not” bool boolnot Truenot False True False not
117 Boolean operations ― “not” >>> not 6 < 7 False 6 < 7 True not False >>> not 6 > 7 True 6 > 7 False not True
118 Ambiguity in expressions 3 + 6 / 3 (3 + 6) / 3 3 + (6 / 3) 3 5 ✘✘✘ ✔✘✘✘✘✘✘
119 Division before addition 5 3 6 / 3+ 3 2+ Division first Addition second
120 “Order of precedence” x**y x*yx/yx%y x+yx-y+x-x x==y x>yx>=yx!=y x<yx<=y not x x or yx and y First Last
121 Progress Comparisons == != < > <= >= Booleans True False Numerical comparison Alphabetical ordering 5 < 7 'dig' < 'dug' Boolean operators and or not Conversions '' 0 0.0 False False False other True
122 Exercise 5 3 minutes Predict whether these expressions will evaluate to True or False. Then try them. 'dog' > 'Cat' or 45 % 3 == 0 'sparrow' > 'eagle' 60 - 45 / 5 + 10 == 1 1. 2. 3.
123 Names and values: “assignment” >>> alpha = 100 1. alpha = 100 2. alpha = 100 int 100 Python creates an “integer 100” in memory. int 100alpha Python attaches the name “alpha” to the value.
124 Assignment: right to left alpha 100= “RHS”: right hand side Evaluated first “LHS”: left hand side Processed second
125 Simple evaluations >>> beta = 100 + 20 RHS1. 100 20+ int 100 function + int 20 int 1202. int 1203. beta LHS
126 Changing value — 1 >>> gamma = 1 >>> gamma = 2
127 Changing value — 2 >>> gamma = 1 int 1 RHS
128 Changing value — 3 >>> gamma = 1 int 1gamma LHS
129 Changing value — 4 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 RHS
130 Changing value — 5 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 LHS
131 Changing value — 6 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 ✘ garbage collection
132 Changing value — 7 >>> gamma = 1 >>> gamma = 2 gamma int 2
133 Changing value — a subtlety >>> gamma = 1 >>> gamma = 2 gamma int 2 int 1 ✘ Two separate integer objects. Python doesn’t change an integer’s value; Python replaces the integer. Python integers are “immutable”
134 Names on the RHS — 1 >>> delta = alpha + 40 RHS 1. alpha 40+ function + int 40int 100 alpha int 140 2. 3.
135 Names on the RHS — 2 >>> delta = alpha + 40 LHS 4. delta int 140
136 Same name on both sides — 0 delta int 140 Starting position >>> print(delta) 140
137 Same name on both sides — 1 >>> delta = delta + 10 RHS 1. delta 10+ function + int 10int 140 delta int 150 2. 3. 4.
138 Same name on both sides — 2 >>> delta = delta + 10 5. 6. LHS int 150 int 140delta RHS int 150 int 140delta RHS
139 Same name on both sides — 3 >>> delta = delta + 10 7. 8. LHS int 150delta int 150 int 140delta ✗ No longer used.
140 “Syntactic sugar” thing += 10 thing = thing + 10 thing -= 10 thing = thing - 10 thing *= 10 thing = thing * 10 thing /= 10 thing = thing / 10 thing **= 10 thing = thing ** 10 thing %= 10 thing = thing % 10 is equivalent to
141 Deleting a name ― 1 >>> print(thing) Traceback (most recent call last): File "<stdin>", line 1, in <module> >>> thing = 1 >>> print(thing) 1 NameError: name 'thing' is not defined Unknown variable
142 Deleting a name ― 2 >>> print(thing) Traceback (most recent call last): File "<stdin>", line 1, in <module> >>> del thing >>> print(thing) 1 NameError: name 'thing' is not defined Unknown variable Known variable
143 Progress Assignment Strictly right to left += etc. “syntactic sugar” thing = thing + 10 thing = thing + 10 2nd 1st thing += 10 Deletion del thing
144 Our first “real” program 1.414213562373095 $ Number? python3 sqrt.py 2.0 We have to write sqrt.py First, the maths. Then, the Python.
145 Square root of 2.0 by “bisection” “Interval of uncertainty” 0.0 too small for √2 2.0 too large for √2 0.0 < √2 < 2.0
146 Square root of 2.0 by bisection — 1 Mid-point: 1.0 (0.0 + 2.0) / 2.0 1.0 1.0**2 1.0
147 Square root of 2.0 by bisection — 2 1.0**2 < 2.0 1.0 < √2 < 2.0 so change lower bound midpoint √2 22 <
148 Square root of 2.0 by bisection — 3 Mid-point: 1.5 (1.0 + 2.0) / 2.0 1.5 1.5**2 2.25
149 Square root of 2.0 by bisection — 4 1.5**2 > 2.0 so change upper bound 1.0 < √2 < 1.5
150 Square root of 2.0 by bisection — 5 Mid-point: 1.25 (1.0 + 1.5) / 2.0 1.25 1.25**2 1.5625
151 Square root of 2.0 by bisection — 6 1.25**2 < 2.0 so change lower bound 1.25 < √2 < 1.5
152 Square root of 2.0 by bisection — 7 Mid-point: 1.375 (1.25 + 1.5) / 2.0 1.375 1.375**2 1.890625
153 Square root of 2.0 by bisection — 8 1.375**2 < 2.0 so change lower bound 1.375 < √2 < 1.5
154 Exercise 6 1.375 < √2 < 1.5 One more iteration. Find the mid-point. Square it. Compare the square to 2.0. Do you change the lower or upper bound? 2 minutes
155 Understanding before Programming
156 And now using Python! lower = 0.0 upper = 2.0 middle = (lower+upper)/2
157 And now using Python — 2 middle**2 < 2.0 True lower = middle print(lower, upper) 2.01.0
158 And now using Python — 3 middle = (lower+upper)/2 print( middle**2)middle, 2.251.5
159 And now using Python — 4 middle**2 < 2.0 False upper = middle print(lower, upper) 1.51.0
160 And now using Python — 5 middle = (lower+upper)/2 print( middle**2)middle, 1.56251.25
161 And now using Python — 6 middle**2 < 2.0 True lower = middle print(lower, upper) 1.51.25
162 And now using Python — 7 middle = (lower+upper)/2 print( middle**2)middle, 1.8906251.375
163 And now using Python — 8 middle**2 < 2.0 True lower = middle print(lower, upper) 1.51.375
164 Looking at the Python code lower = 0.0 upper = 2.0 middle = (lower+upper)/2 print(middle, middle**2) middle**2 < 2.0 lower = middle upper = middle ?✔ ✘ print(lower, upper)
165 Looking at the Python structures lower = 0.0 upper = 2.0 middle = (lower+upper)/2 print(middle, middle**2) middle**2 < 2.0 lower = middle upper = middle ?✔ ✘ print(lower, upper) Set up Loop Choice
166 Looping Before Loop test Loop body After ✘ ✔ Should the loop run (again)? What is run each loop?
167 Loop example: Count from 1 to 10 number = 1 number <= 10 print(number) number += 1 print('Done!') ✘ ✔ Before Loop test Loop body After ✘ ✔
168 Loop example: Count from 1 to 10 number = 1 number <= 10 print(number) number += 1 print('Done!') ✘ ✔ number = 1 while print(number) number += 1 print('Done!') :number <= 10 ␣␣␣␣ ␣␣␣␣
169 Loop test: Count from 1 to 10 number = 1 while print('Done!') :number <= 10 “while” keyword loop test colon print(number) number += 1 ␣␣␣␣ ␣␣␣␣
170 Loop body: Count from 1 to 10 number = 1 while print('Done!') :number <= 10 loop body indentation print(number) number += 1 ␣␣␣␣ ␣␣␣␣
171 number = 1 while number <= 10 : print(number) number += 1 print('Done!') Loop example: Count from 1 to 10 while1.py $ 1 2 3 4 5 6 7 8 9 10 Done! python3 while1.py $
172 Python’s use of indentation number = 1 while number <= 10 : p ␣␣␣␣ ␣␣␣␣ print(number) number += 1 Four spaces’ indentation indicate a “block” of code. The block forms the repeated lines. The first unindented line marks the end of the block. rint('Done!')
173 c.f. “legalese” 1 1(a) 1(b) 1(b)(i) 1(b)(ii) 1(b)(iii) 1(c) 2 3
174 Other languages Shell C while ... do ␣␣␣␣... ␣␣␣␣... done while ... { ␣␣␣␣... ␣␣␣␣... } do ... done { ... } Syntax Syntax ␣␣␣␣... ␣␣␣␣... Clarity Clarity
175 Progress while ... : before while test : ␣␣␣␣action1 ␣␣␣␣action2 ␣␣␣␣action3 afterwards test to keep looping code blocks ␣␣␣␣indentation
176 Exercise 7 5 minutes For each script: Predict what it will do. Run the script. Were you right? while2.py while3.py while4.py while5.py␣␣␣␣ ␣␣␣␣ ␣␣␣␣ To kill a running script: Ctrl C+ while6.py
177 1.51.375 Back to our square root example 1.0 2.0 1.0 0.0 2.0 2.0 1.0 1.5 0.5 1.25 1.5 0.25 0.125 ×½ ×½ ×½ ×½ uncertainty 1.0×10–15 tolerance What we get What we want
178 Keep looping while … ? tolerance>uncertainty while uncertainty > tolerance : ␣␣␣␣ ␣␣␣␣ ␣␣␣␣ ␣␣␣␣ Do stuff.
179 Square root: the loop lower = 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) ? Set up Loop Choice
180 Choosing middle**2 < 2.0 lower = middle upper = middle ?✔ ✘ Choice middle**2 < 2.0 True Falseor True False lower = middle upper = middle
181 Simple example text = input('Number? ') number = int(text) if number % 2 == 0: print('Even number') else: print('Odd number') print('That was fun!') ifthenelse1.py $ Number? Even number That was fun python3 ifthenelse1.py $ Number? Odd number That was fun python3 ifthenelse1.py 8 7
182 if…then… else… ― 1 if else : ␣␣␣␣print('Even number') ␣␣␣␣upper = middle :number % 2 == 0 if keyword Test Colon print('That was fun!')
183 if…then… else… ― 2 if else : ␣␣␣␣ print('Even number') ␣␣␣␣upper = middle :number % 2 == 0 Run if test is True Indentation print('That was fun!')
184 if…then… else… ― 3 if else : ␣␣␣␣print('Even number') ␣␣␣␣ upper = middle :number % 2 == 0 else: keyword Run if test is False Indentation print('That was fun!')
185 if…then… else… ― 4 if else : ␣␣␣␣print('Even number') ␣␣␣␣ upper = middle :number % 2 == 0 Run afterwards regardless of test print('That was fun!')
186 Our square root example middle = (lower + upper)/2 if else : print(lower, upper) ␣␣␣␣lower = middle ␣␣␣␣upper = middle Before :middle**2 < 2.0 After if… block
187 Progress if ... : before if test : ␣␣␣␣action1 ␣␣␣␣action2 else: ␣␣␣␣action3 afterwards else: choice of two code blocks ␣␣␣␣indentation
188 Exercise 8 5 minutes For each script: Predict what it will do. Run the script. Were you right? ifthenelse2.py ifthenelse3.py ifthenelse4.py ␣␣␣␣ ␣␣␣␣ ␣␣␣␣
189 Back to our example lower = 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) if middle**2 < 2.0 : else : upper = middle lower = middle Doubly indented if starts indented
190 Levels of indentation lower = 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) if middle**2 < 2.0 : else : upper = middle lower = middle ␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣ 4 spaces 8 spaces
191 Trying it out tolerance = 1.0e-15 lower = 0.0 upper = 2.0 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 if middle**2 < 2.0: lower = middle else: upper = middle print(lower, upper) uncertainty = upper - lower sqrt1.py $ 1.0 2.0 1.0 1.5 1.25 1.5 1.375 1.5 1.375 1.4375 1.40625 1.4375 1.40625 1.421875 ... 1.414213... 1.414213... python3 sqrt1.py ☺
192 Script for the square root of 2.0 lower = 0.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) upper = 2.0 if middle**2 < 2.0 : else : upper = middle lower = middle ␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣ √2.0 √2.0
193 Input target text = input('Number? ') number = float(text) if middle**2 < number : …
194 Initial bounds? x > 1.0 1.0 < √x < x 1.0 > x 1.0 > √x > x lower = ? upper = ? if...then...else...
195 Initial bounds if number < 1.0 : ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else : ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number
196 Generic square root script? text = input('Number?␣') number = float(text) if number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance: ␣␣␣␣middle = (lower+upper)/2.0 ␣␣␣␣if middle**2 < number: ␣␣␣␣␣␣␣␣lower = middle ␣␣␣␣else: ␣␣␣␣␣␣␣␣upper = middle ␣␣␣␣uncertainty = upper - lower print(lower, upper) User input Initialization Processing Output sqrt2.py
197 exit()␣␣␣␣ Negative numbers? Need to catch negative numbers if number < 0.0: ␣␣␣␣print('Number must be positive!') Quit immediately "else" is optional
198 “Chained” tests text = input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number must be positive!') ␣␣␣␣exit() if number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number ... User input Input validation Initialization
199 elif “Chained” tests ― syntactic sugar text = input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number must be positive!') ␣␣␣␣exit() number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number ... elif: “else if” sqrt3.py
200 Without elif… text = input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number is negative.') else: ␣␣␣␣if number < 1.0: ␣␣␣␣␣␣␣␣print('Number is between zero and one.') ␣␣␣␣else: ␣␣␣␣␣␣␣␣if number < 2.0: ␣␣␣␣␣␣␣␣␣␣␣␣print('Number is between one and two.') ␣␣␣␣␣␣␣␣else: ␣␣␣␣␣␣␣␣␣␣␣␣if number < 3.0: ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣print('Number is between two and three.') ␣␣␣␣␣␣␣␣␣␣␣␣else: ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣print('Number is three or more.') Stacked clauses get unwieldy
201 With elif… text = input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number is negative.') elif number < 1.0: ␣␣␣␣print('Number is between zero and one.') elif number < 2.0: ␣␣␣␣print('Number is between one and two.') elif number < 3.0: ␣␣␣␣print('Number is between two and three.') else: ␣␣␣␣print('Number is three or more.')
202 Progress Nested structures if … : … elif … : … elif … : … else: … while … : if … : Chained tests Testing inputs to scripts exit()
203 Exercise 9 10 minutes exercise9.py 1. Edit the square root script to catch negative numbers. Only attempt each part after you have the previous part working! 2. Edit the square root script to ask for the tolerance. 3. Edit the square root script to catch negative tolerances.
204 Comments We have written our first real Python script What did it do? Why did it do it? Need to annotate the script
205 Python comment character The “hash” character Lines starting with “#” are ignored Partial lines starting “#” are ignored Used for annotating scripts # a.k.a. “pound”, “number”, “sharp”
206 Python commenting example # Script to calculate square roots by bisection # (c) Bob Dowling 2012. Licensed under GPL v3.0 text = input('Number?␣') number = float(text) # Need a real number # Test number for validity, # set initial bounds if OK. if number < 0.0: ␣␣␣␣print('Number must be non-negative!') ␣␣␣␣exit() elif number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number
207 On a real Unix system… #!/usr/bin/python3 # Script to calculate square roots by bisection # (c) Bob Dowling 2012. Licensed under GPL v3.0 text = input('Number?␣') number = float(text) # Need a real number Magic line for executable files $ instead of fubar.py $ python3 fubar.py
208 Progress Comments #“#” character
209 Exercise 10 2 minutes Comment your square root script from exercise 9.
210 Recap: Python types so far Whole numbers Floating point numbers Text Booleans -127 3.141592653589793 'The cat sat on the mat.' True False Complex numbers (1.0 + 2.0j)
211 Lists [ 'hydrogen', 'helium', 'lithium', 'beryllium', 'boron', …, 'thorium', 'protactinium', 'uranium' ] [ -3.141592653589793, -1.5707963267948966, 0.0, 1.5707963267948966, 3.141592653589793 ] [ 2, 3, 5, 7, 11, 13, 17, 19 ]
212 What is a list? A sequence of values Individual value identified by position in the sequence The names of the elements “helium” is the name of the second element Values stored in order Atomic number order hydrogen, helium, lithium, beryllium, …, protactinium, uranium
213 What is a list? A sequence of values Individual value identified by position in the sequence The prime numbers less than sixty 7 is the fourth prime Values stored in order Numerical order 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59
214 Creating a list in Python >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> type(primes) <class 'list'> The whole list A Python type A literal list
215 How Python presents lists [ ]1917,13,11,7,5,3 ,,2 Square brackets at the ends Commas between items
216 Square brackets primes = [2, 3, 5, 7, 11] Literal list
217 Python counts from zero [ ]1917,13,11,7,5,3 ,,2 76543210“index” “value”
218 Looking things up in a list >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> primes 2 >>> 17 ]0[ index primes ]6[ square brackets
219 Square brackets primes = [2, 3, 5, 7, 11] Literal list primes[3] Index into list
220 Counting from the end >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> 19 primes ]-1[ getting at the last item -1-2-3-4-5-6-7-8
221 Inside view of a list list 8 int 19 … primes int 17 int 3 int 2 primes[0] primes[1] primes[6] primes[7]
222 Length of a list primes list 8 >>> len 8 (primes) 0 7 Maximum index is 7 len() function: length of list
223 Changing a value in a list >>> data = ['alpha', 'beta', 'gamma'] >>> data[2] 'gamma' >>> data[2] = 'G' >>> data[2] 'G' >>> data ['alpha', 'beta', 'G'] The list Initial value Change value Check change Changed list
224 Changing a value in a list ― 1 >>> data = ['alpha', 'beta', 'gamma'] list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a Right to left
225 Changing a value in a list ― 2 >>> data = ['alpha', 'beta', 'gamma'] data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a Right to left
226 Changing a value in a list ― 3 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a str 1 G New value
227 Changing a value in a list ― 4 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a str 1 G No longer referenced
228 Changing a value in a list ― 5 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 1 G
229 Removing an entry from a list ― 1 >>> del data[1] data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a data[0] data[1] data[2] ✗
230 Removing an entry from a list ― 2 >>> del data[1] data list 2 str 5 a l p h a str 4 b e t a str 5 g a m m a data[0] data[1] No longer referenced
231 Removing an entry from a list ― 3 >>> del data[1] data list 2 str 5 a l p h a str 5 g a m m a data[0] data[1]
232 Running off the end list 8 int 19 … primes int 17 int 3 int 2 primes[8]
233 Running off the end >>> len(primes) 8 >>> primes[7] 19 >>> primes[8] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range Type of error Description of error
234 Running off the end >>> primes[8] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range Same type of error Similar description of error but with “assignment”
235 Progress Lists index Count from zero Length Over-running [2, 3, 5, 7, 11, 13, 17, 19] primes[4] primes[0] len(primes) primes[8] Deletion del primes[6]
236 Exercise 11 5 minutes Track what the value of numbers is at each stage of this sequence of instructions. numbers = [5, 7, 11, 13, 17, 19, 29, 31]>>> numbers[1] = 3>>> del numbers[3]>>> numbers[3] = 37>>> numbers[4] = numbers[5]>>> 1 2 3 4 5
237 How can we add to a list? list 8 int 19 … int 17 int 2 list 9 int 19 … int 17 int 2 int 23 ? Same list Extra item New length
238 Appending to a list >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> primes >>> primes [2, 3, 5, 7, 11, 13, 17, 19, (23)append. The list is now updated ]23 A function built into a list
239 primes.append() ? >>> primes (23)append. The list A connecting dot append() The value to append All lists have this function built in.
240 “Methods” (arguments)object function. a function that has special access to the object’s data. Behaves just like a function
241 Using the append() method >>> print(primes) [2, 3, 5, 7, 11, 13, 17, 19] >>> primes (23)append. >>> primes (29)append. >>> primes (31)append. >>> primes (37)append. >>> print(primes) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] The function doesn’t return any value. It modifies the list itself.
242 Other methods on lists: reverse() >>> numbers = [4, 7, 5, 1] >>> numbers.reverse() >>> print(numbers) [1, 5, 7, 4] The function doesn’t return any value. It modifies the list itself.
243 Other methods on lists: sort() >>> numbers = [4, 7, 5, 1] >>> numbers.sort() >>> print(numbers) [1, 4, 5, 7] Numerical order. The function does not return the sorted list. It sorts the list itself.
244 Other methods on lists: sort() >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek.sort() >>> print(greek) ['alpha', 'beta', 'delta', 'gamma'] Alphabetical order of the words.
245 Other methods on lists: insert() >>> greek = 'gamma',['alpha', 0 1 2 >>> greek.insert( 'delta'] Where to insert What to insert 'beta'1, ) >>> greek ['alpha', 'gamma', 'delta']'beta', 1 Displaced 0
246 Other methods on lists: remove() >>> numbers = [7, 4, >>> numbers.remove >>> print(numbers) [7, 4, 7, 2, 5, 4]8, (8) 7, 2, 5, 4] c.f. del numbers[2] Value to remove Index to remove
247 Other methods on lists: remove() >>> >>> numbers.remove >>> print(numbers) [7, (4) print(numbers) [7, 7, 2, 5,4, 4] 7, 2, 5, 4] Only the first instance is removed There are two instances of 4.
248 What methods are there? >>> help(numbers) Help on list object: class list(object) ... | append(...) | L.append(object) -- append object to end ... Pagination: ␣ B next page back one page Q quit
249 Help on a single method >>> help(numbers.append) Help on built-in function append: append(...) L.append(object) -- append object to end
250 Sorting a list redux >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek.sort() >>> print(greek) ['alpha', 'beta', 'delta', 'gamma'] Recall: greek.sort() sorts the list “in place”.
251 Sorting a list redux: “sorted()” >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> print(sorted(greek)) >>> print(greek) ['alpha', 'beta', 'gamma', 'delta'] sorted() function returns a sorted list… ['alpha', 'beta', 'delta', 'gamma'] …and leaves the list alone
252 Adding to a list redux: “+” >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> primes [2, 3, 5, 7, 11, 13, 17, 19, [23, 29, 31]+ 23, 29, 31] Concatenation operator List to add
253 Concatenation >>> newlist >>> >>> primes = primes + [23, 29, 31] primes = primes + [23, 29, 31] Create a new list Update the list [23, 29, 31]+= Augmented assignment
254 Creating lists from text ― 1 >>> list('Hello') ['H', 'e', 'l', 'l', 'o'] str 5 H e l l o list 5 str 1 H str 1 e str 1 l str 1 l str 1 o
255 Creating lists from text ― 2 >>> 'Hello, world!' ['Hello,', 'world!'] list 2 H e l l o , ␣ w o r l d !13str str 6 H e l l o , str 6 w o r l d ! .split() Built in method Splits on spaces
256 Progress “Methods” append(item) reverse() sort() insert(index,item) remove(item) Concatenation + += object.method(arguments) [1,2,3] + [4,5,6] primes += [29, 31] Sorting list.sort() sorted(list) Help help(object) help(object.method)
257 Exercise 12 5 minutes
258 Is an item in a list? ― 1 >>> odds = [3, 5, 7, 9] Does not include 2 >>> odds.remove(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Hard error list.remove(x): x not in list x must be in the list before it can be removed Try to remove 2 ✗
259 Is an item in a list? ― 2 >>> odds = [3, 5, 7, 9] >>> 2 in odds False >>> 3 in odds True >>> 2 not in odds True
260 Precedence x**y x*yx/yx%y x+yx-y+x-x x==y x>yx>=yx!=y x<yx<=y not x x or yx and y First Last x not in y x in y The list now contains every operator we meet in this course.
261 Safe removal if number in numbers : numbers.remove(number) while number in numbers : numbers.remove(number) What’s the difference?
262 Working through a list ― 1 e.g. Printing each element on a line ['The', 'cat', 'sat', 'on', 'the', 'mat.'] The cat sat on the mat.
263 Working through a list ― 2 e.g. Adding the elements of a list [45, 76, -23, 90, 15] 203 What is the sum of an empty list? [] ?
264 Working through a list ― 3 e.g. Squaring every number in a list [4, 7, -2, 9, 1] [16, 49, 4, 81, 1]
265 The “for loop” ― 1 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for ␣␣␣␣ :wordsinword print(word) name of list list A new Python looping construct print: What we want to do with the list items.
266 The “for loop” ― 2 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for ␣␣␣␣ :wordsinword print(word) keywords colon followed by an indented block
267 word) The “for loop” ― 3 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for :wordsinword print( Defining the loop variable Using the loop variable ␣␣␣␣
268 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ First loop
269 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Second loop
270 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Third loop
271 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Fourth loop
272 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Fifth loop
273 Running the “for loop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Final loop
274 The “for loop” for printing word) words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for :wordsinword print(␣␣␣␣ for1.py
275 The “for loop” for adding numbers = [45, 76, -23, 90, 15] for :in total += total = 0 number numbers print(total) number Set up before the loop Processing in the loop Results after the loop ␣␣␣␣ for2.py
276 The “for loop” for creating a new list numbers = [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers print(squares) Set up before the loop Processing in the loop Results after the loop number**2)␣␣␣␣ for3.py
277 The loop variable persists! numbers = [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers print( number**2)␣␣␣␣ )number Loop variable only meant for use in loop! But it persists!
278 “for loop hygeine” numbers = [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers del number**2)␣␣␣␣ number Delete it after use
279 Progress Testing items in lists for loops 3 in [1,2,3,4] total = 0 for number in [1,2,3,4]: total += number del number True loop variables for number in [1,2,3,4]: total += number del number
280 Exercise 13 5 minutes What does this print? numbers = [0, 1, 2, 3, 4, 5] total = 0 total_so_far = [] for number in numbers: total += number total_so_far.append(total) print(total_so_far)
281 “Sort-of-lists” Python “magic”: Treat it like a list and it will behave like a useful list What can “it” be?
282 Strings as lists Recall: list('Hello') ['H', 'e', 'l', 'l', 'o'] for letter in H e l l o print(letter) :'Hello' Gets turned into a list. for4.py
283 Creating lists of numbers Built in to Python: range(start,limit) for number in print(number) :range(3,8) 3 4 5 6 7 8 not included
284 ranges of numbers Not actually lists: >>> range(0,5) range(0,5) But close enough: >>> [0, 1, 2, 3, 4] list(range(0,5)) Treat it like a list and it will behave like a list
285 Why not just a list? Most common use: for number in … range(0, 10000): Inefficient to make a huge list just for this “iterator” : anything that can be treated like a list list(iterator) Explicit list
286 Ranges of numbers again range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(3, 10) [3, 4, 5, 6, 7, 8, 9] range(3, 10, 2) [3, 5, 7, 9] via list() Start at 0 Every nth number range(10, 3, -2) [10, 8, 6, 4] Negative steps
287 Indices of lists >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> len(primes) >>> list(range( 8 [0, 1, 2, 3, 4, 5, 6, 7] 8)) valid indices
288 Direct value or via the index? primes = [2, 3, 5, 7, 11, 13, 17, 19] for prime in primes: print(prime) for index in range(len(primes)): print(primes[index]) Equivalent Simpler
289 Working with two lists: “dot product” list1 = [ 0.4]0.0,0.3, list2 = [ 0.6]0.5,0.2, ××× 0.240.00.06 + + 0.3 ∙
290 Working with two lists: indices list1 = [0.3, 0.0, 0.4] list2 = [0.2, 0.5, 0.6] for index in sum = 0.0 print(sum) 0 1 2 indices :range(len(list1)) sum += list1[index]*list2[index] Dealing with values from both lists at the same time.
291 iter 4 2 A little more about iterators ― 1 str 5 a l p h a str 4 b e t a str 5 g a m m a str 5 d e l t a >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek_i = iter(greek) >>> next(greek_i) 'alpha' >>> next(greek_i) 'beta' Offset
292 iter 4 ✗ A little more about iterators ― 2 str 5 a l p h a str 4 b e t a str 5 g a m m a str 5 d e l t a >>> next(greek_i) 'gamma' >>> next(greek_i) 'delta' >>> next(greek_i) Traceback (most recent call last): File "<stdin>", line 1, in <module> ✗StopIteration
293 Progress Non-lists as lists “Iterators” range() Indices of lists Parallel lists range(limit) range(start,limit) range(start,limit,step) range(3,7) [3,4,5,6] for letter in 'Hello': ... for index in range(len(things)): greek_i = iter(greek) next(greek_i)
294 Exercise 14 5 minutes list1 = [ 0.4]0.0,0.3, list2 = [ 0.6]0.5,0.2, -0.2-0.50.1 Complete exercise14.py 0.040.250.01 0.3++ Difference Square Add
295 List “slices” primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]>>> primes>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] primes[3]>>> 7 primes[3:9]>>> [7, 11, 13, 17, 19, 23] The list An item Part of the list
296 Slices ― 1 primes = [2, 3, 5, 7, 11, 13, 17, 19, 29, 31] 3 9 [7,primes[3:9] Item 9 not included 23, 11, 13, 17, 19, 23] primes[ ]9:3 to from Up to but not including…
297 Slices ― 2 primes 7, 11, 13, 17, 19, 29, 31]23, primes[ ]9:3 [7, 11, 13, 17, 19, 23] [2, 3, 5, primes[ ]9: [2, 3, 5, 7, 11, 13, 17, 19, 23] primes[ ]:3 [7, 11, 13, 17, 19, 23, 29, 31] primes[ ]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
298 Slices ― 3 primes 7, 11, 13, 17, 19, 29, 31]23, primes[ ]9:3 [7, 11, 13, 17, 19, 23] [2, 3, 5, primes[ :9:3 [7, 13, 19 ]]2 primes[ :9:3 ]3 [7, 17 ]
299 list 3 alphabet letters Copies and slices ― 1 letters = ['a','b','c']>>> str 1 a str 1 b str 1 c alphabet = letters>>>
300 list 3 alphabet letters Copies and slices ― 2 letters[0] = 'A'>>> str 1 A str 1 b str 1 c print(alphabet)>>> ['A', 'b', 'c']
301 letters alphabet list 3 Copies and slices ― 3 letters = ['a','b','c']>>> str 1 a str 1 b str 1 c alphabet = letters[:]>>> list 3 Slices are copies.
302 Copies and slices ― 4 letters[0] = 'A'>>> print(alphabet)>>> Slices are copies. ['a', 'b', 'c'] letters alphabet list 3 str 1 a str 1 b str 1 c list 3 str 1 A
303 Progress Slices items[from:to] items[:to] items[from:] items[:] items[from:to:stride] items[:to:stride] items[from::stride] items[::stride] End-limit excluded Slices are copies
304 Exercise 15 3 minutes Predict what this Python will do. Then run it. Were you right? exercise15.py foo = [4, 6, 2, 7, 3, 1, 9, 4, 2, 7, 4, 6, 0, 2] bar = foo[3:12:3] bar[2] += foo[4] foo[0] = bar[1] print(bar)
305 list 5 Diversion: Lists and strings Text: “a string of characters” list() str 1 H str 1 e str 1 l str 1 l str 1 o str 5 H e l l o
306 Indexing into strings 'Hello, world!'[0]>>> 'H' 'Hello, world!'[:4]>>> 'Hell' Simple indexing Slicing
307 Strings are immutable 'Hello, world!'[0] = 'C'>>> Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
308 Files .txt .dat .csv Reading Writing Input Output
309 Reading a text file File name File object File contents 'treasure.txt' book 'TREASURE ISLAND' string file string “opening” the file reading from the file Finished with the file “closing” the file
310 Opening a text file >>> book )'r','treasure.txt'(open= Read-only [text] File name Python function Python file object “mode” book )'treasure.txt'(open= Read-only is the default
311 Reading from a file object >>> line1 book= File object First line of file >>> line1 ' n'TREASURE ISLAND Includes the “end of line” next( ) “next line, please”
312 File object are iterable >>> line2 next(book)= Second line of file >>> line2 'n' >>> line3 next(book)= >>> line3 'PART ONEn' A blank line Third line of file
313 Closing the file >>> .close()book Method built in to file object Frees the file for other programs to write to it.
314 The file object ― 1 >>> book <_io.TextIOWrapper encoding='UTF-8'> name='treasure.txt' Text Input/Output File name Character encoding: how to represent letters as numbers.
315 The file object ― 2 file 29 treasure.txt UTF-8 TREASURE ISLAND↵ ↵ PART ONE↵ ↵ The Old Buccaneer↵ ↵ ☞ Pointer to the file on the file system “offset”: how far into the file we have read File name Text encoding
316 Reading through a file Treat it like a list and it will behave like a list list(file_object) List of lines in the file >>> book = open('treasure.txt', 'r') >>> lines = list(book) >>> print(lines)
317 Reading a file moves the offset !>>> book = open('treasure.txt', 'r') >>> lines_a = list(book) >>> print(lines_a) >>> lines_b = list(book) >>> print(lines_b) [] Empty list Huge output…
318 Reading a file moves the offset >>> book >>> lines_a = >>> print(lines_a) >>> >>> print(lines_b) [] … File object starts with offset at start. = open('treasure.txt', 'r') Operation reads entire file from offset. list(book) lines_b = list(book) Offset changed to end of file. Operation reads entire file from offset. So there's nothing left to read.
319 Resetting the offset >>> book >>> lines_a = >>> print(lines_a) >>> >>> … = open('treasure.txt', 'r') list(book) lines_b = list(book) >>> print(lines_b) book.seek(0) Set the offset explicitly
320 Typical way to process a file book = open('treasure.txt', 'r') for line in book : … Treat it like a list…
321 Example: lines in a file book = open('treasure.txt', 'r') n_lines = 0 for line in book : n_lines += 1 print(n_lines) Line count Read each line of the file Increment the count Print out the count book.close()
322 Example: characters in a file book = open('treasure.txt', 'r') n_chars = 0 for line in book : n_chars print(n_chars) len(line) Number of characters on the line Increase the count by that many += book.close()
323 Progress Opening file to read Reading file Closing file File offset book = open(filename, 'r') book.close() book.seek(0) for line in book: ...
324 Exercise 16 5 minutes Complete a script to count lines, words and characters of a file. exercise16.py
325 Writing files File name Data to write File object 'treasure.txt' book 'TREASURE ISLAND' string file string “opening” the file writing to the file Finished with the file “closing” the file
326 Opening a text file for writing >>> output )'w','output.txt'(open= Open for writing [text] ! This will truncate an existing file
327 Opening a text file for appending >>> output )'a','output.txt'(open= Open for appending [text]
328 Writing to a file object ― 1 >>> .writeoutput Method built in to file object File object (line1) Data being written6 Number of characters actually written >>> len(line1) 6
329 Writing to a file object ― 2 >>> .writeoutput ('alpha Typical use: whole line. Includes “end of line” n') >>> .writeoutput ('be') >>> .writeoutput ('tan') Doesn’t have to be whole lines >>> .writeoutput ('gammandeltan') Can be multiple lines 6 2 3 12
330 Closing the file object >>> .close()output Vital for written files
331 Importance of closing Data “flushed” to disc on closure. Python script File object File system write “flush” !
332 Importance of closing promptly ! Files locked for other access open ['w'] open ['r'] ✗ (More a problem for Windows than Unix)
333 Writing non-text values >>> output.write('Boo!n') Writing text (str) 5 >>> output.write(42) Writing non-text (int) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not int write() only accepts text ✗
334 Writing non-text values >>> output.write( Convert to text: str() 2 >>> output.write('n') Explicit end-of-line 1 str(42)) Text formatting (later in the course) provides a more elegant solution.
335 Progress Opening files for writing Explicit ends of lines book = open(filename, 'w') book.write('n') Writing data book.write(str(data)) Writing text book.write(text) Closing the file is important book.close()
336 Exercise 17 5 minutes The script exercise17.py prints a series of numbers ending in 1. Change the script to write to a file called output.txt instead of printing to the console.
337 Functions y = f(x)
338 Functions we have met print(line) open(filename, mode) range(from, to, stride) float(thing) int(thing) iter(list) str(thing) len(thing) type(thing) input(prompt) Not that many! “The Python Way”: If it is appropriate to an object, make it a method of that object. bool(thing) ord(char) chr(number) list(thing)
339 Why write our own functions? … read … test … fix … improve … add to … write Easier to … “Structured programming” … develop
340 Defining a function (y1 , y2 , y3 ) (x1 , x2 , x3 , x4 , x5 )= f Identify the inputs Identify the processing Identify the outputs
341 A function to define: total() Sum a list [1, 2, 3] [7, -4, 1, 6, 0] [ ] 6 10 0 “Edge case”
342 Defining a Python function ― 1 def :( … )total colon inputs name of function define a function called …
343 Defining a Python function ― 2 def total( ):numbers name for the input This name is internal to the function.
344 Defining a Python function ― 3 def total(numbers): Colon followed by indentation ⇨
345 Defining a Python function ― 4 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number “Body” of function
346 Defining a Python function ― 4 def total( ):numbers sum_so_far for sum_so_far += number = 0 in numbers:number These variables exist only within the function’s body.
347 Defining a Python function ― 5 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far This value is returned return this value
348 Defining a Python function ― 6 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far And that’s it! Unindented after this
349 Defining a Python function ― 7 And that’s it! All internal names cleaned up No need for del All internal names internal No need to avoid reusing names
350 Using a Python function ― 1 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) The list we want to add up
351 Using a Python function ― 2 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) The function we have just written
352 Using a Python function ― 3 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) Printing out the answer
353 Using a Python function ― 4 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) total1.py $ python3 total1.py 6 nb: Unix prompt
354 Using a Python function ― 5 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) print(total([7,-4,1,6,0])) print(total([])) total2.py $ python3 total2.py 6 10 0 Use the function multiple times
355 Functions’ private names ― 1 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far data = [1, 2, 3] data_sum = total(data) print(data_sum) Function definition Main script
356 Functions’ private names ― 2 def total(numbers): ... total main script function “namespace”
357 Functions’ private names ― 3 data = [1, 2, 3] list 3 int 1 int 2 int 3 total data main script function
358 Functions’ private names ― 4 ... = total(data) total data main script list 3 int 1 int 2 int 3 def total(numbers): total numbers function
359 Functions’ private names ― 5 ... = total(data) total function data main script list 3 int 1 int 2 int 3 sum_so_far = 0 total numbers sum_so_far int 0
360 Functions’ private names ― 6 ... = total(data) total function data main script list 3 int 1 int 2 int 3 return sum_so_far total numbers sum_so_far int 6
361 Functions’ private names ― 7 data_sum = total(data) total function data main script list 3 int 1 int 2 int 3 return sum_so_far total numbers sum_so_far int 6 data_sum
362 Functions’ private names ― 8 data_sum = total(data) total function data main script list 3 int 1 int 2 int 3 int 6 data_sum
363 Progress Functions “Structured programming” Defining a function Returning a value def function(input): ... return output Private name spaces
364 Exercise 18 5 minutes Edit the script exercise18.py. It currently defines and uses a function total() which adds the elements of a list. Change it to create a function product() which multiplies them. Three examples are included in the script. Running it should produce the following output: $ python3 exercise18.py 6 0 1
365 Reminder about indices def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far def total(numbers): sum_so_far = 0 for index in range(len(numbers)): sum_so_far += numbers[index] return sum_so_far Equivalent total3.py total2.py
366 Want a function to add two lists of the same length term-by-term: Example of multiple inputs [1, 2, 3] [5, 7, 4] [6, 9, 7]& [10, -5] [15, 14] [25, 9]& [11, 11, -2, 2, 7][3, 7, 4, 1, 7] [8, 4, -6, 1, 0]& Two inputs
367 Functions with multiple inputs def add_lists( sum_list = [] for sum sum_list.append(sum) return sum_list ):b_list,a_list :range(len(a_list))inindex b_list[index]+a_list[index]= Multiple inputs are separated by commas
368 Functions with multiple inputs def add_lists( sum_list = [] for sum sum_list.append(sum) return sum_list ):b_list,a_list :range(len(a_list))inindex b_list[index]+a_list[index]= We have two lists… …so we have to use indexing
369 Multiple outputs Write a function to find minimum and maximum value in a list [1, 2, 3] [10, -5] [3, 7, 4, 1, 7] Two outputs 1 & -5 & 1 & 3 10 7
370 Finding just the minimum def min_list(a_list): min_so_far = a_list[0] for if a < min_so_far: return :a_listina min_so_far = a min_so_far Returning a single value List cannot be empty! minlist.py
371 Finding just the maximum def max_list(a_list): max_so_far = a_list[0] for if a > max_so_far: return :a_listina max_so_far = a max_so_far Returning a single value Only real change maxlist.py
372 Finding both def minmax_list(a_list): max_so_far = a_list[0] for if a > max_so_far: return what? :a_listina max_so_far = a min_so_far = a_list[0] if a < min_so_far: min_so_far = a This is the real question
373 Returning both def minmax_list(a_list): max_so_far = a_list[0] for if a > max_so_far: return :a_listina max_so_far = a min_so_far = a_list[0] if a < min_so_far: min_so_far = a min_so_far, max_so_far A pair of values minmaxlist.py
374 “Tuples” e.g. min_value max_value, min_value avg_value, max_value, Pair Triple Often written with parentheses: min_value max_value, min_value avg_value, max_value, ( ( ) ) Commas
375 Using tuples to return values min_value max_value,return minimum In the function definitiondef … Using the function = minmax_list(values)maximum,
376 Using tuples to attach names alpha =beta, 56,12 alpha = beta 56 12 = ( ) ( )
377 Swapping values >>> alpha = 12 >>> beta = 56 >>> (alpha, beta) = (beta, alpha) >>> print(alpha) 56 >>> print(beta) 12 Swapping values
378 Assignment works right to left alpha = 12 beta = 56 (alpha, beta) = (beta, alpha) Stage 1: (beta, alpha) (56, 12) Stage 2: (alpha, 12)(56,=beta)
379 Progress Multiple inputs Multiple outputs “Tuples” Simultaneous assignment def thing(in1 , in2 , in3 ): return (out1 , out2 , out3 ) (a, b, c) (a, b) = (a+b, a-b)
380 Exercise 19 10 minutes The script exercise19.py is an answer to exercise 16. Edit it to: 1. define a function file_stats() that takes a file name and returns a triple (n_lines, n_words, n_chars) 2. use input() to read in a file name 3. use file_stats() with that file name 4. end with print(filename, file_stats(filename))
381 Tuples and lists: similarities >>> >>>x = ['alpha','beta'] y = ('alpha','beta') >>> >>>x[1] y[1] 'beta' 'beta' >>> >>>len(x) len(y) 2 2 >>> (a, b) = (1, 2) >>> a 1 >>> [c, d] = [1, 2] >>> c 1 Indexing Length Simultaneous asignment
382 Tuples and lists: differences >>> >>>x = ['alpha','beta'] y = ('alpha','beta') >>> >>>x[1] = 'B' y[1] = 'B' >>> x ['alpha','B'] TypeError: 'tuple' object does not support item assignment Lists are mutable Tuples are immutable
383 Tuples and lists: philosophy Sequential: Concept of “next item” Lists Tuples Simultaneous: All items “at once” Best with all items of the same type Safe to have multiple types [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] ('Dowling', 'Bob', 50, 105.0, 'rjd4') Sequence of prime numbers Surname, forename, age, weight, user id Serial Parallel
384 Functions we have written so far total(list) add_lists(list1 ,list2 ) minmax_list(list)
385 Reusing functions within a script def square(limit): ... ... squares_a = square(34) ... five_squares = squares(5) ... squares_b = squares(56) ... One definition Multiple uses in the same file Easy!
386 ... squares_a = squares(34) ... ... five_squares = squares(5) ... Reusing functions between scripts? def squares(limit): ... One definition How? ... squares_b = squares(56) ... Multiple uses in multiple files
387 “Modules” def ... square(limit) five = squares(5) : ... ... Definition Use Module: a container of functions def ... cubes(limit):
388 def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far text = input('Number? ') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) Modules: a worked example ― 1a sum_squares.py Starts empty utils.py
389 Modules: a worked example ― 1b $ python3 sum_squares.py Number? 5 30 $ python3 sum_squares.py Number? 7 91 = 0 + 1 + 4 + 9 + 16 = 0 + 1 + 4 + 9 + 16 + 25 + 36
390 text = input('Number? ') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) Modules: a worked example ― 2a def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py sum_squares.py Move the definitions into the other file.
391 Modules: a worked example ― 2b $ python3 sum_squares.py Number? 5 Traceback (most recent call last): File "sum_squares.py", line 4, in <module> squares_n = squares(number) NameError: name 'squares' is not defined Because we have (re)moved its definition.
392 Modules: a worked example ― 3a import utils text = input('Number? ') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py sum_squares.py import: Make a reference to the other file. import utils and not import utils.py
393 Modules: a worked example ― 3b $ python3 sum_squares.py Number? 5 Traceback (most recent call last): File "sum_squares.py", line 4, in <module> squares_n = squares(number) NameError: name 'squares' is not defined Still can’t find the function(s).
394 Modules: a worked example ― 4a import utils text = input('Number? ') number = int(text) squares_n = utils.squares(number) total_n = utils.total(squares_n) print(total_n) sum_squares.py utils.…: Identify the functions as coming from the module. squares() utils.squares() total() utils.total()
395 Modules: a worked example ― 4b $ python3 sum_squares.py Number? 5 30 $ python3 sum_squares.py Number? 7 91 Working again! ☺
396 Progress Sharing functions between scripts “Modules” Importing modules Using functions from modules import module module.function()
397 Exercise 20 5 minutes The script exercise20.py is an answer to exercise19. Move the function file_stats() from exercise19.py into utils.py and edit exercise19.py so that it still works.
398 The Python philosophy math sys string A small core language … … plus lots of modules “Batteries included”
399 Example: the “math” module >>> import >>> math. 1.4142135623730951 math Load in the “math” module. Run the sqrt() function… … from the math module. 2.0)sqrt(
400 import module as alias >>> import math >>> math. 1.4142135623730951 >>> import math as >>> m 1.4142135623730951 sqrt(2.0) Too long to keep typing? m .sqrt(2.0) “Alias”
401 Don’t do these >>> from math import sqrt >>> sqrt(2.0) 1.4142135623730951 >>> from math import * >>> sqrt(2.0) 1.4142135623730951 ! !! Much better to track the module.
402 What system modules are there? sys os string re csvargparse webbrowser math cmath colorsys pickle datetime email getpass glob html http io json logging random signal sqlite3 subprocess tempfile unicodedata unittest xml Python 3.2.3 comes with over 250 modules.
403 “Batteries included” >>> help('modules') Please wait a moment while I gather a list of all available modules... CDROM binascii inspect shlex bdb importlib shelve Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". 263 modules Not quite this simple
404 Additional downloadable modules numpy scipy psycopg2 MySQLdb cx_oracle ibm_db pyodbc Numerical PostgreSQL MySQL Oracle DB2 Databases pymssql SQL Servermatplotlib Graphics
405 An example system module: sys import sys print(sys.argv) argv.py $ python3 argv.py one two three ['argv.py', $ python3 argv.py 1 2 3 ['argv.py', '3']'2','1', Always strings 'three']'two','one', 0 1 2 3index
406 sys.exit() exit() What we have been using sys.exit What we should use(rc) “Return Code”: an integer 0: Everything was OK ≠0:Something went wrong
407 An example system module: sys But also… sys.path sys.version sys.modules sys.stdin sys.stdout sys.stderr Directories Python searches for modules Version of Python All modules currently imported Where input inputs from Where print prints to Where errors print to …and there’s more! sys.float_info All the floating point limits
408 Modules in Python “How do I do X in Python?” “What’s the Python module to do X?” “Where do I find Python modules?”
409 Finding modules Python: PyPI: Built-in modules Python Package Index SciPy: Scientific Python modules Search: “Python3 module for X”
410 Help with modules >>> import math >>> help(math) NAME math DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. …
411 Help with module functions … FUNCTIONS acos(x) Return the arc cosine (measured in radians) of x. … >>> math.acos(1.0) 0.0
412 Help with module constants DATA e = 2.718281828459045 pi = 3.141592653589793 … … >>> math.pi 3.141592653589793
413 Help for our own modules? def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py >>> import utils >>> help(utils) NAME utils FUNCTIONS squares(limit) total(numbers) FILE /home/y550/utils.py Basic help already provided by Python
414 Adding extra help text def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py >>> help(utils) NAME utils >>> import utils Fresh start"""Some utility functions from the Python for Absolute Beginners course """ FUNCTIONS squares(limit) total(numbers) DESCRIPTION Some utility functions from the Python for Absolute Beginners course
415 Adding extra help text to functions """Some utility functions from the Python for Absolute Beginners course """ def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer utils.py """Returns a list of squares from zero to limit**2. """ >>> help(utils) NAME utils DESCRIPTION ... >>> import utils Fresh start FUNCTIONS squares(limit) Returns a list of squares from zero to limit**2.
416 Adding extra help text to functions """Some utility functions from the Python for Absolute Beginners course """ def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer utils.py """Returns a list of squares from zero to limit**2. """ >>> help(utils.squares) >>> import utils Fresh start squares(limit) Returns a list of squares from zero to limit**2.
417 Progress Python a small language… …with many, many modules System modules Modules provide help Foreign modules Doc strings Functionality Module help(module) help(module.function)
418 Exercise 21 5 minutes Add help text to your utils.py file.
419 Recap: Lists & Indices list 3 Position 2 Position 1 Position 0 greek = ['alpha', 'beta', 'gamma'] str 5 a l p h a str 4 b e t a str 5 g a m m a greek[0] greek[1] greek[2]
420 “Index in ― Value out” listindex value 1 greek 'beta'[1] Must be a number start at 0 no gaps in sequence
421 Other “indices”: Strings? dictionaryEnglish Spanish 'cat' 'dog' 'mouse' 'gato' 'perro' 'ratón' dictionary
422 Other “indices”: Tuples? dictionary(x, y) Objects (2,5) (4,5) 'Treasure' 'Fortress' dictionary
423 Python “dictionaries” >>> en_to_es = { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['cat'] 'gato'
424 Creating a dictionary — 1 'dog':'perro'{ },'cat':'gato' Curly brackets Comma 'cat' → 'gato' 'dog' → 'perro'
425 Creating a dictionary — 2 'dog'{ },'cat' 'gato': 'perro': 'cat' 'gato' “key” “value” : :
426 Using a dictionary — 1 >>> en_to_es = { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['cat'] 'gato' Creating the dictionary Using the dictionary
427 Using a dictionary — 2 en_to_es ]'cat'[ 'gato' dictionary key value Square brackets
428 Missing keys >>> en_to_es = { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['dog'] 'perro' >>> en_to_es['mouse'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'mouse' Error message ✓ ✗
429 Dictionaries are one-way ! >>> en_to_es = >>> en_to_es['dog'] 'perro' >>> en_to_es['perro'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: ✓ ✗ 'perro' Looking for a key { }'dog':,'cat': 'perro''gato'
430 Adding to a dictionary >>> en_to_es >>> en_to_es['mouse'] = 'ratón' >>> en_to_es['mouse'] 'ratón' = { 'cat':'gato' , 'dog':'perro' } Initial dictionary has no 'mouse' Adding 'mouse' to the dictionary
431 Removing from a dictionary >>> print(en_to_es) {'mouse': 'ratón', >>> del en_to_es[ >>> print(en_to_es) {'mouse': 'ratón', 'cat': 'gato'} 'cat': 'gato'}'dog': 'perro', ]'dog'
432 Progress Dictionaries Key Value { key1 :value1 , key2 :value2 , key3 :value3 } dictionary[key] valueLooking up values dictionary[key] = valueSetting values del dictionary[key]Removing keys
433 Exercise 22 5 minutes Complete exercise22.py to create an English to French dictionary. cat chat dog chien mouse souris snake serpent
434 What’s in a dictionary? ― 1 >>> en_to_es {'mouse': 'ratón', 'dog': 'perro', 'cat': 'gato'} >>> en_to_es.keys() dict_keys >>> en_to_es.values() dict_values Just treat them like lists Orders match (['mouse', 'dog', 'cat']) (['ratón', 'perro', 'gato']) (or convert them to lists)
435 What’s in a dictionary? ― 2 >>> en_to_es dict_items([('mouse', 'ratón'), ('dog', 'perro'), ('cat', 'gato')]) >>> for (english, spanish) in en_to_es.items(): ... print(spanish, english) ... ratón mouse perro dog gato cat Most useful method.items() (Key,Value) pairs/tuples
436 What’s in a dictionary? ― 3 >>> list [('mouse','ratón'), ('dog','perro'),('cat','gato')] Common simplification (en_to_es.items())
437 Getting the list of keys dictionary list of keys list() {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1} ['on', 'the', 'sat', 'mat', 'cat']
438 Is a key in a dictionary? >>> en_to_es['snake'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'snake' Want to avoid this >>> 'snake' in en_to_es False We can test for it
439 Example: Counting words ― 1 words = ['the','cat','sat','on','the','mat'] counts = {'the':2,'cat':1,'sat':1,'on':1,'mat':1}
440 Example: Counting words ― 2 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: Do something Start with an empty dictionary Work through all the words
441 Example: Counting words ― 3 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: counts[word] += 1 ✗ This will not work counter1.py
442 Why doesn’t it work? counts = {'the':1, 'cat':1} counts['the'] += 1 counts['sat'] += 1 ✗ ✓ counts['the'] = + 1counts['the'] The key must already be in the dictionary. counts['sat'] = + 1counts['sat'] Key is not in the dictionary!
443 Example: Counting words ― 4 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: if word in counts: counts[word] += 1 else: Do something Need to add the key
444 Example: Counting words ― 5 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 counter2.py print(counts)
445 Example: Counting words ― 6 $ python3 counter2.py {'on': 1, 'the': 2, 'sat': 1, 'mat': 1, 'cat': 1} You cannot predict the order of the keys when a dictionary prints out. !
446 Example: Counting words ― 7 print(counts) items = list(dictionary.items()) items.sort() for (key, value) in items: print(key, value) ✗ Too ugly Better counter3.py
447 Example: Counting words ― 8 $ python3 counter3.py cat 1 mat 1 on 1 sat 1 the 2
448 Progress Testing keys in dictionaries Creating a list of keys if key in dictionary: ... keys = list(dictionary) Inspection methods dictionary.keys() dictionary.values() dictionary.items()
449 Exercise 23 5 minutes Complete exercise23.py to write a script that reverses a dictionary. { { 'perro'}'dog':'gato','cat':'ratón','mouse': :'dog'}'perro''cat','gato':'mouse','ratón':
450 Formatted output $ python3 counter3.py cat 1 mat 1 sat 1 the 2 on 1 Ugly! cat mat on sat the 1 1 1 1 2 We want data nicely aligned
451 The format() method >>> 'xxxAyyy100zzz' 'xxx{}yyy{}zzz'.format('A', 100) ' ' zzz{}yyy{}xxx ' 'zzz100yyyAxxx
452 String formatting ― 1 >>> 'xxxA␣␣␣␣yyy' 'xxx{:5s}yyy'.format('A') ' ' yyy{:5s}xxx ' 'yyyA␣␣␣␣xxx {:5s} s ― substitute a string 5 ― pad to 5 spaces (left aligns by default)
453 String formatting ― 2 >>> 'xxxA␣␣␣␣yyy' 'xxx{:<5s}yyy'.format('A') ' ' yyy{:<5s}xxx ' 'yyyA␣␣␣␣xxx {:<5s} < ― align to the left (←)
454 String formatting ― 3 >>> 'xxx␣␣␣␣Ayyy' 'xxx{:>5s}yyy'.format('A') ' ' yyy{:>5s}xxx ' 'yyy␣␣␣␣Axxx {:>5s} > ― align to the right (→)
455 Integer formatting ― 1 >>> 'xxx␣␣123yyy' 'xxx{:5d}yyy'.format(123) ' ' yyy{:5d}xxx ' 'yyy␣␣123xxx {:5d} d ― substitute an integer 5 ― pad to 5 spaces (right aligns by default) (digits)
456 Integer formatting ― 2 >>> 'xxx␣␣123yyy' 'xxx{:>5d}yyy'.format(123) ' ' yyy{:>5d}xxx ' 'yyy␣␣123xxx {:>5d} > ― align to the right (→)
457 Integer formatting ― 3 >>> 'xxx␣␣123yyy' 'xxx{:>5d}yyy'.format(123) ' ' yyy{:<5d}xxx ' 'yyy123␣␣xxx {:<5d} < ― align to the left (←)
458 Integer formatting ― 4 >>> 'xxx00123yyy' 'xxx{:05d}yyy'.format(123) ' ' yyy{:05d}xxx ' 'yyy00123xxx {:05d} 0 ― pad with zeroes
459 Integer formatting ― 5 >>> 'xxx␣+123yyy' 'xxx{:+5d}yyy'.format(123) ' ' yyy{:+5d}xxx ' 'yyy␣+123xxx {:05d} + ― always show sign
460 Integer formatting ― 6 >>> 'xxx␣+0123yyy' 'xxx{:+05d}yyy'.format(123) ' ' yyy{:+05d}xxx ' 'yyy+0123xxx {:05d} + ― always show sign 0 ― pad with zeroes
461 Integer formatting ― 7 >>> 'xxx1,234yyy' 'xxx{:5,d}yyy'.format(1234) ' ' yyy{:5,d}xxx ' 'yyy1,234xxx {:5,d} , ― 1,000s
462 Floating point formatting ― 1 >>> 'xxx 1.20yyy' 'xxx{:5.2f}yyy'.format(1.2) ' ' yyy{:5.2f}xxx ' 'yyy␣1.20xxx {:5.2f} f ― substitute a float 5 ― 5 places in total .2 ― 2 places after the point
463 Floating point formatting ― 2 >>> 'xxx1.200000yyy' 'xxx{:f}yyy'.format(1.2) ' ' yyy{:f}xxx ' 'yyy1.200000xxx {:f} {:.6f}
464 Ordering and repeats ― 1 >>> 'X 'X )1.23123,'abc',X'.format({:f}X{:d}X{:s} X'1.230000X123Xabc 0 1 2 0 1 2 0 1 2 >>> 'X )1.23123,'abc',X'.format({2:f}X{1:d}X{0:s} 'X X'1.230000X123Xabc 0 1 2 0 1 2 Equivalent
465 Ordering and repeats ― 2 >>> 'X )1.23123,'abc',X'.format({2:f}X{1:d}X{0:s} 'X X1.230000 X123Xabc 0 12 0 1 2 ' >>> 'X )1.23123,'abc',X'.format(X{1:d}X{0:s} 'X X123Xabc 0 1 0 1 2 X' {1:d} 123 1
466 Formatting in practice $ python3 counter4.py cat mat on sat the 1 1 1 1 2 ... formatting = '{:3} {:1}' for (word, number) in items: print(formatting.format(word,number)) $
467 Progress string.format(args)Formatting Numbered parameters Substitutions {0} {1} {2} {:>6s} {:+06d} {:+012.7f}
468 Exercise 24 5 minutes Complete exercise24.py to format the output as shown: Joe 9 Samantha 45 Methuselah 969 [(Joe,9), (Samantha,45), (Methuselah,969)]
469 And that's it! (And “it” is a lot!) Text Prompting Numbers Arithmetic Comparisons Booleans Variables Deleting names “while” loop “if” test Indented blocks Lists Indices Object methods Built-in help “for” loops “Treat it like a list…” Values direct/via index Reading files Writing files Functions “Structured programming” Tuples “for” loops Modules Dictionaries Formatting
470 But wait! There’s more… Advanced topics: Self-paced introductions to modules Object-oriented programming in Python
471 Text Prompting Numbers Arithmetic Comparisons Booleans Variables Deleting names “while” loop “if” test Indented blocks Lists Indices Object methods Built-in help “for” loops “Treat it like a list…” Values direct/via index Reading files Writing files Functions “Structured programming” Tuples “for” loops Modules Dictionaries Formatting Congratulations! Please don’t forget the feedback.

An introduction to Python for absolute beginners

  • 1.
    1 An introduction toPython for absolute beginners
  • 2.
    2 Sources ● An introductionto Python for absolute beginners Bob Dowling University Information Services scientific-computing@ucs.cam.ac.uk http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB ● Introduction to Python Chen Lin clin@brandeis.edu ● Learn Python the hard way http://learnpythonthehardway.org/book/ ● http://python.org/
  • 3.
    3 Advices ● Go througheach exercise. ● Type in each sample exactly. ● Make it run. ● Reading and Writing ● Attention to Detail ● Spotting Differences ● Do Not Copy-Paste ● A Note on Practice and Persistence
  • 4.
    4 Course outline ―1 Who uses Python & what for What sort of language it is How to launch Python Python scripts Reading in user data Numbers Conversions Comparisons Names for values Text and Comments Truth & Falsehood
  • 5.
    5 Course outline ―2 Assignment Names Our first “real” program Loops if… else… Indentation
  • 6.
    6 Course outline ―3 Lists Indices Lengths Changing items Extending lists Methods Creating lists Testing lists Removing from lists for… loop Iterables Slices
  • 7.
    7 Course outline ―4 Files Reading & writing Writing our own functions Tuples Modules System modules External modules Dictionaries Formatted text
  • 8.
    8 What is Python ●Cross platform ● Multi-purpose (Web, GUI, Scripting, …) ● Object Oriented ● Interpreted ● Stringly typed ● Dynamically typed ● Focus on readability and productivity ● Powerful
  • 9.
    9 Features ● Everything isan Object ● Interactive shell ● IDE ● Huge ecosystem
  • 10.
    10 History ● Created in1989 by Guido Van Rossum ● 1994 – Python 1.0 ● 2000 – Python 2.0 ● 2008 – Python 3.0
  • 11.
    11 Who uses Python? On-linegames Web services Applications Science Instrument control Embedded systems en.wikipedia.org/wiki/List_of_Python_software
  • 12.
    12 What sort oflanguage is Python? Explicitly compiled to machine code Purely interpreted C, C++, Fortran Shell, Perl Explicitly compiled to byte code Java, C# Implicitly compiled to byte code Python Compiled Interpreted
  • 13.
    Major versions ofPython ● “Python” or “CPython” is written in C/C++ – Version 2.7 came out in mid-2010 – Version 3.1.2 came out in early 2010 – Latest stable version is 3.5.1 of 3.x series ● “Jython” is written in Java for the JVM ● “IronPython” is written in C# for the .Net environment ● PyPy Go To Website
  • 14.
    Downloading Python ● https://www.python.org/downloads –3.5.1 ● Download Windows x86-64 executable installer – 2.7.11 ● Download Windows x86-64 MSI installer
  • 15.
  • 16.
  • 17.
    17 Running Python ―2 $ python3 Unix prompt Unix command Introductory blurb Python prompt [GCC 4.6.3] on linux2 (default, May 3 2012, 15:54:42) Python version Python 3.2.3 >>>
  • 18.
    18 Quitting Python >>> exit() >>>quit() >>> Ctrl D+ Any one of these
  • 19.
    19 PEP 8 ● PythonEnhancement Proposals (PEP) – https://www.python.org/dev/peps/ ● PEP 8 – Style Guide for Python Code – https://www.python.org/dev/peps/pep-0008/
  • 20.
    20 A first Pythoncommand >>> print('Hello, world!') Hello, world! >>> Python prompt Python command Output Python prompt
  • 21.
    21 Python commands print Python “function” ( Function’s“argument” Round brackets ― “parentheses” ( )'Hello, world!' “Case sensitive”print PRINT≠
  • 22.
    22 Python text The body ofthe text Quotation marks ' 'Hello, world! ! The quotes are not part of the text itself.
  • 23.
    23 Python comments ● Notes,examples in a single or multiple lines ● Single line: # print('Hello, world!') ● Multiple lines: ''' You can writhe anything here: print('Hello, world!') Same in English '''
  • 24.
  • 25.
  • 26.
    26 Python scripts hello1.py File inhome directory $ python3 Hello, world! $ Unix prompt Unix command to run Python Python script Python script’s output Unix prompt hello1.py print('Hello, world!') Run from Unix prompt
  • 27.
  • 28.
  • 29.
    Development Environments what IDEto use? http://stackoverflow.com/questions/81584 1. PyDev with Eclipse 2. Komodo 3. Emacs 4. Vim 5. TextMate 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows) 10.BlueFish (Linux)
  • 30.
  • 31.
  • 32.
  • 33.
    33 Exercise 1 1. Print“Rock and roll” from interactive Python. 2. Edit exercise1.py to print the same text. 3. Run the modified exercise1.py script. 2 minutes ❢ Please ask if you have questions.
  • 34.
    34 A little moretext hello2.py print(' эłℏ Ꮣዐ, ω☺ ∂‼')ⲗրFull “Unicode” support www.unicode.org/charts/
  • 35.
    35 Getting characters ğ AltGr Shift+#+ g “LATIN SMALL LETTER G WITH BREVE” u011f Character Selector Linux ˘
  • 36.
    36 Text: a “string”of characters >>> type('Hello, world!') <class 'str'> A string of characters H e l l o , ␣ w o r l d !13 Class: string Length: 13 Letters str
  • 37.
    37 Text: “behind thescenes” str 13 72 101 108 108 111 44 32 33100… 011f16 ğ >>> chr(287) 'ğ' >>> ord('ğ') 287 >>> 'u011f' 'ğ' 28710
  • 38.
    38 Adding strings together:+ print('Hello, ' + 'world!') hello3.py “Concatenation” >>> 'Hello, ' + 'world!' 'Hello, world!' >>>
  • 39.
    39 Pure concatenation >>> 'Hello,␣'+ 'world!' 'Hello, world!' >>> 'Hello,' + '␣world!' 'Hello, world!' >>> 'Hello,' + 'world!' 'Hello,world!' Only simple concatenation No spaces added automatically.
  • 40.
    40 Single & doublequotes >>> 'Hello, world!' 'Hello, world!' >>> 'Hello, world!' Single quotes "Hello, world!" Double quotes Single quotes Single quotes
  • 41.
    41 Python strings: input& output 'Hello, world!' 'Hello, world!' "Hello, world!" Single or double quotes on input. Single quotes on output. Create same string object. H e l l o , ␣ w o r l d !13str
  • 42.
    42 Uses of single& double quotes >>> He said "hello" to her. print('He said "hello" to her.') >>> He said 'hello' to her. print("He said 'hello' to her.")
  • 43.
    43 Why we needdifferent quotes >>> File "<stdin>", line 1 print('He said 'hello' to her.') ^ SyntaxError: invalid syntax print('He said 'hello' to her.') ✘
  • 44.
    44 Adding arbitrary quotes >>>print('He said 'hello' to her.') He said 'hello' to her. ' " ' " “Escaping” Just an ordinary character. H e s a i␣ ' h e l l23str o ' t o h e r .d ␣␣ ␣
  • 45.
    45 Putting line breaksin text >>> print('Hello, Hello, world! What we want world') ↵ Try this >>> print('Hello, ↵ File "<stdin>", line 1 print('Hello, ^ >>> SyntaxError: EOL while scanning string literal “EOL”: End Of Line ✘
  • 46.
    46 Inserting “special” characters >>>print('Hello, Hello, world! world!')n Treated as a new line. str 13 e l l o , ↵ w o r l d !H n Converted into a single character. >>> len 13 len() function: gives the length of the object ('Hello,nworld!')
  • 47.
  • 48.
    48 n: unwieldy forlong text 'SQUIRE TRELAWNEY, Dr. Livesey, and then rest of these gentlemen having asked men to write down the whole particularsnabou t Treasure Island, from thenbeginning to the end, keeping nothingnback but the b earings of the island,nand that only bec ause there is stillntreasure not yet lif ted, I take up mynpen in the year of gra ce 17__ and gonback to the time when my father keptnthe Admiral Benbow inn and t he brownnold seaman with the sabre cut f irstntook up his lodging under our roof.' Single line
  • 49.
    49 Special input methodfor long text Triple quotes ''' rest of these gentlemen having asked me to write down the whole particulars about Treasure Island, from the beginning to the end, keeping nothing back but the bearings of the island, and that only because there is still treasure not yet lifted, I take up my pen in the year of grace 17__ and go back to the time when my father kept the Admiral Benbow inn and the brown old seaman with the sabre cut first took up his lodging under our roof. SQUIRE TRELAWNEY, Dr. Livesey, and the ''' Multiple lines
  • 50.
    50 Python’s “secondary” prompt >>>'''Hello, world'''... Python asking for more of the same command.
  • 51.
    51 It’s still justtext! >>> 'Hello,nworld!' 'Hello >>> ... '''Hello, world!''' 'Hellonworld' world'n Python uses n to represent line breaks in strings. Exactly the same!
  • 52.
    52 Your choice ofinput quotes: 'Hello,nworld!' "Hello,nworld!" """Hello, world!""" '''Hello, world!''' str 13 e l l o , ↵ w o r l d !H Same result: Four inputs:
  • 53.
    53 Progress International text print() Concatenation ofstrings Long strings Special characters
  • 54.
    54 Exercise 2 3 minutes 1.Replace XXXX in exercise2.py so it prints the following text (with the line breaks) and then run the script. coffee Kaffee café caffè é è u00e8 u00e9 AltGr AltGr + + # ; e e
  • 55.
    55 Attaching names tovalues message = 'Hello, world!' print(message) hello3.py str 13 e l l o , ␣ w o r l d !Hmessage “variables” >>> message='Hello, world!' >>> message 'Hello, world!' >>> type(message) <class 'str'>
  • 56.
    56 Attaching names tovalues message = 'Hello, world!' print(message) hello4.py print function str 13 e l l o , ␣ w o r l d !Hmessage >>> type(print) <class 'builtin_function_or_method'>
  • 57.
    57 Reading some textinto a script $ python3 Yes? input1.py Boo! Boo! message = input('Yes?␣') print(message) input1.py input('Yes?␣') message = … print(message)
  • 58.
    58 Can't read numbersdirectly! number = input('N?␣') print(number + 1) input2.py $ python3 input2.py N? 10 Traceback (most recent call last): File "input2.py", line 2, in <module> print( + ) string integer number TypeError: Can't convert 'int' object to str implicitly ✘ 1
  • 59.
    59 input(): strings only number= input('N?␣') print(number + 1) input2.py ✘$ python3 input2.py N? 10 input('N? ')␣ str 2 01 int 10≠
  • 60.
    60 Some more types >>>type('Hello, world!') <class 'str'> >>> type(42) <class 'int'> >>> type(3.14159) <class 'float'> string of characters integer floating point number
  • 61.
    61 Converting text tointegers >>> int('10') 10 >>> int('␣-100␣') -100 >>> int('100-10') ValueError: invalid literal for int() with base 10: '100-10' str 2 01 int 10 str 6 -␣ int -100 01 ␣0 ✘
  • 62.
    62 Converting text tofloats >>> float('10.0') 10.0 >>> float('␣10.␣') 10.0 '10.0' is a string 10.0 is a floating point number
  • 63.
    63 Converting between intsand floats >>> float(10) 10.0 >>> int(10.9) 10 Truncates fractional part >>> int(-10.9) -10
  • 64.
    64 Converting into text >>>str(10) '10' >>> str(10.000) '10.0' integer float string string
  • 65.
    65 Converting between types int() float() anything anything integer float str()anything string Functions named after the type they convert into.
  • 66.
    66 Reading numbers intoa script text = input('N? ')␣ number = int(text) print(number + 1)$ N? 11 python3 input3.py 10
  • 67.
    67 Stepping through ourscript — 1 text = input('N?␣') number = int(text) print(number + 1) str 3 ?N ␣
  • 68.
    68 Stepping through ourscript — 2 text = input('N?␣') number = int(text) print(number + 1) str 3 ?N ␣ input function str 2 01 NB: text, not number
  • 69.
    69 Stepping through ourscript — 3 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text
  • 70.
    70 Stepping through ourscript — 4 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text int function int 10
  • 71.
    71 Stepping through ourscript — 5 text = input('N? ')␣ number = int(text) print(number + 1) input function str 2 01text int function int 10number
  • 72.
    72 Stepping through ourscript — 6 text = input('N? ')␣ number = int(text) print(number + 1) int 10number
  • 73.
    73 Stepping through ourscript — 7 text = input('N? ')␣ number = int(text) print(number + 1) int 10number function int 11 + int 1
  • 74.
    74 Stepping through ourscript — 6 text = input('N? ')␣ number = int(text) print(number + 1) int 10number int 11 functionprint
  • 75.
    75 Progress Names Types Type conversions Values Reading intext str() int() float() input(prompt) name = value strings integers floating point numbers
  • 76.
    76 Exercise 3 Replace thetwo XXXX in exercise3.py to do the following: 1. Prompt the user with the text “How much?␣”. 2. Convert the user’s answer to a floating point number. 3. Print 2.5 plus that number. 3 minutes
  • 77.
    77 Integers ℤ{… -2, -1,0, 1, 2, 3, 4 …}
  • 78.
    78 Integer addition &subtraction >>> 20+5 25 >>> 20␣-␣5 15 Spaces around the operator don’t matter. “No surprises”
  • 79.
    79 Integer multiplication There isno “×” on the keyboard. Linux: ,+ShiftAltGr + Use “*” instead >>> 20␣*␣5 100 Still no surprises
  • 80.
    80 Integer division There isno “÷” on the keyboard. Linux: .+ShiftAltGr + Use “/” instead >>> 20␣/␣5 4.0 This is a floating point number! Surprise!
  • 81.
    81 Integer division givesfloats ! Fractions >>> 20␣/␣40 0.5 >>> 20␣/␣30 0.6666666666666666 Floats sometimes Consistency Floats always !
  • 82.
    82 Integer division givesfloats ! >>> 20␣//␣4 5 ! // Special operation to stick with integers >>> 21␣//␣4 5 >>> -21␣//␣4 -6 >>> 20␣/␣4 5.0 >>> 21␣/␣4 5.25 >>> -21␣/␣4 -5.25
  • 83.
    83 Integer powers There isno “42 ” on the keyboard. Use “**” instead >>> 4␣**␣2 16 >>> 4*␣*2 SyntaxError: invalid syntax Spaces around the operator don’t matter. Spaces in the operator do!
  • 84.
    84 Integer remainders e.g. Isa number even or odd? >>> 4␣%␣2 0 >>> 5␣%␣2 1 Use “%” >>> -5␣%␣2 1 Remainder is always non-negative
  • 85.
    85 How big cana Python integer be? >>> 2**2 4 >>> 4**2 16 >>> 16**2 256 >>> 256**2 65536 >>> 65536**2 4294967296 >>> 256**2 65536 >>> 256**2 65536 >>> 2**2 4
  • 86.
    86 How big cana Python integer be? >>> 4294967296**2 18446744073709551616 >>> 18446744073709551616**2 340282366920938463463374607431768211456 >>> 340282366920938463463374607431768211456**2 1157920892373161954235709850086879078532699846 65640564039457584007913129639936 >>> 115792089237316195423570985008687907853269 1340780792994259709957402499820584612747936582 0592393377723561443721764030073546976801874298 1669034276900318581864860508537538828119465699 46433649006084096 984665640564039457584007913129639936**2
  • 87.
    87 How big cana Python integer be? 10443888814131525066917527107166243825799642490473837803842334832839 53907971557456848826811934997558340890106714439262837987573438185793 60726323608785136527794595697654370999834036159013438371831442807001 18559462263763188393977127456723346843445866174968079087058037040712 84048740118609114467977783598029006686938976881787785946905630190260 94059957945343282346930302669644305902501597239986771421554169383555 98852914863182379144344967340878118726394964751001890413490084170616 75093668333850551032972088269550769983616369411933015213796825837188 09183365675122131849284636812555022599830041234478486259567449219461 70238065059132456108257318353800876086221028342701976982023131690176 78006675195485079921636419370285375124784014907159135459982790513399 61155179427110683113409058427288427979155484978295432353451706522326 90613949059876930021229633956877828789484406160074129456749198230505 71642377154816321380631045902916136926708342856440730447899971901781 46576347322385026725305989979599609079946920177462481771844986745565 92501783290704731194331655508075682218465717463732968849128195203174 57002440926616910874148385078411929804522981857338977648103126085903 00130241346718972667321649151113160292078173803343609024380470834040 3154190336 There is no limit! Except for machine memory
  • 88.
    88 Big integers 2 4 16 256 65536 4294967296 18446744073709551616 3402823669209384634… 63374607431768211456 C /C++ Fortran Out of the reach of C or Fortran! long long INTEGER*16 long INTEGER*8 int INTEGER*4
  • 89.
  • 90.
    90 Basic operations >>> 20.0+ 5.0 25.0 >>> 20.0 - 5.0 15.0 >>> 20.0 * 5.0 100.0 >>> 20.0 / 5.0 4.0 >>> 20.0 ** 5.0 3200000.0 Equivalent to integer arithmetic
  • 91.
    91 Floating point imprecision >>>1.0 / 3.0 0.3333333333333333 >>> 10.0 / 3.0 3.3333333333333335 ≈ 17 significant figures If you are relying on this last decimal place, you are doing it wrong!
  • 92.
    92 Hidden imprecision >>> 0.1 0.1 >>>0.1 + 0.1 0.2 >>> 0.1 + 0.1 + 0.1 0.30000000000000004 Really: if you are relying on this last decimal place, you are doing it wrong! !
  • 93.
    93 How big cana Python float be? ― 1 >>> 65536.0**2 4294967296.0 >>> 4294967296.0**2 1.8446744073709552e+19 So far, so good. Switch to “scientific notation” 1.8446744073709552 1.8446744073709552 ×1019 e+19
  • 94.
    94 Floats are notexact >>> 4294967296**2 18446744073709551616 >>> 4294967296.0**2 1.8446744073709552e+19 Integer Floating point 1.8446744073709552×1019 18446744073709552000 18446744073709551616- 384
  • 95.
    95 How big cana Python float be? ― 2 >>> 1.8446744073709552e+19**2 3.402823669209385e+38 >>> 3.402823669209385e+38**2 1.157920892373162e+77 >>> 1.157920892373162e+77**2 1.3407807929942597e+154 >>> 1.3407807929942597e+154**2 OverflowError: (34, 'Numerical result out of range') So far, so good. Too big!
  • 96.
    96 Floating point limits 1.2345678901234567×10N 17significant figures -325 < N < 308 4.94065645841×10-324 < N < 8.98846567431×10307 Positive values:
  • 97.
  • 98.
    98 Progress Arithmetic Integers Floating point numbers Complexnumbers + - * / ** % No limits! Limited size Limited precision
  • 99.
    99 Exercise 4 3 minutes Replacethe XXXX in exercise4.py to evaluate and print out the following calculations: 1. 223 ÷ 71 2. (1 + 1/100)100 3. (1 + 1/10000)10000 4. (1 + 1/1000000)1000000 Note: Brackets work in Python arithmetic just like they do in normal mathematics.
  • 100.
    100 Comparisons 5 < 10 5> 10 ✘✘✘ ✔ ✘✘✘✘✘✘
  • 101.
    101 Comparisons >>> 5 <10 True >>> 5 > 10 False Asking the question Asking the question ✘✘✘ ✔ ✘✘✘✘✘✘
  • 102.
    102 True & False >>>type(True) <class 'bool'> “Booleans” 5 10+ 5 10< int int 15 True int bool
  • 103.
    103 True & False bool✓ bool ✗ True False Only two values
  • 104.
  • 105.
    105 Equality comparison &assignment name = value = value1 == value2 == Attach a name to a value. Compare two values
  • 106.
    106 Textual comparisons >>> 'cat'< 'dog' True Alphabetic ordering >>> 'Cat' < 'cat' True >>> 'Dog' < 'cat' True Uppercase before lowercase All uppercase before lowercase
  • 107.
    107 Ordering text iscomplicated German: Swedish: z < ö ö < z Python inequalities use Unicode character numbers. This is over-simplistic for “real” use. Alphabetical order? “Collation” is a whole field of computing in itself
  • 108.
    108 “Syntactic sugar” 0 <number < 10 0 < number and number < 10 >>> number = 5 >>> 0 < number < 10 True
  • 109.
    109 Converting to booleans float()Converts to floating point numbers int() Converts to integers str() Converts to strings bool() Converts to booleans <class 'float'> <class 'int'> <class 'str'> <class 'bool'>
  • 110.
    110 Useful conversions 'Fred' True ''False Non-empty string Empty string 1 True 0 False Non-zero Zero 12 True -1 True
  • 111.
    111 Boolean operations Numbers have+, –, * … What do booleans have? bool ✓ bool ✗ bool bool bool?
  • 112.
    112 Boolean operations ―“and” bool bool booland True Trueand True Falseand False Trueand False Falseand True False False False Both have to be True
  • 113.
    113 Boolean operations ―“and” >>> 4 < 5 and 6 < 7 True 4 < 5 6 < 7 True True and True >>> 4 < 5 and 6 > 7 False 4 < 5 6 > 7 True False and False
  • 114.
    114 Boolean operations ―“or” bool bool boolor True Trueor True False False True False False True False True True At least one has to be Trueor or or
  • 115.
    115 Boolean operations ―“or” >>> 4 < 5 or 6 < 7 True 4 < 5 6 < 7 True True or True >>> 4 < 5 or 6 > 7 True 4 < 5 6 > 7 True False or True
  • 116.
    116 Boolean operations ―“not” bool boolnot Truenot False True False not
  • 117.
    117 Boolean operations ―“not” >>> not 6 < 7 False 6 < 7 True not False >>> not 6 > 7 True 6 > 7 False not True
  • 118.
    118 Ambiguity in expressions 3+ 6 / 3 (3 + 6) / 3 3 + (6 / 3) 3 5 ✘✘✘ ✔✘✘✘✘✘✘
  • 119.
    119 Division before addition 5 36 / 3+ 3 2+ Division first Addition second
  • 120.
    120 “Order of precedence” x**yx*yx/yx%y x+yx-y+x-x x==y x>yx>=yx!=y x<yx<=y not x x or yx and y First Last
  • 121.
    121 Progress Comparisons == !=< > <= >= Booleans True False Numerical comparison Alphabetical ordering 5 < 7 'dig' < 'dug' Boolean operators and or not Conversions '' 0 0.0 False False False other True
  • 122.
    122 Exercise 5 3 minutes Predictwhether these expressions will evaluate to True or False. Then try them. 'dog' > 'Cat' or 45 % 3 == 0 'sparrow' > 'eagle' 60 - 45 / 5 + 10 == 1 1. 2. 3.
  • 123.
    123 Names and values:“assignment” >>> alpha = 100 1. alpha = 100 2. alpha = 100 int 100 Python creates an “integer 100” in memory. int 100alpha Python attaches the name “alpha” to the value.
  • 124.
    124 Assignment: right toleft alpha 100= “RHS”: right hand side Evaluated first “LHS”: left hand side Processed second
  • 125.
    125 Simple evaluations >>> beta= 100 + 20 RHS1. 100 20+ int 100 function + int 20 int 1202. int 1203. beta LHS
  • 126.
    126 Changing value —1 >>> gamma = 1 >>> gamma = 2
  • 127.
    127 Changing value —2 >>> gamma = 1 int 1 RHS
  • 128.
    128 Changing value —3 >>> gamma = 1 int 1gamma LHS
  • 129.
    129 Changing value —4 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 RHS
  • 130.
    130 Changing value —5 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 LHS
  • 131.
    131 Changing value —6 >>> gamma = 1 >>> gamma = 2 int 1gamma int 2 ✘ garbage collection
  • 132.
    132 Changing value —7 >>> gamma = 1 >>> gamma = 2 gamma int 2
  • 133.
    133 Changing value —a subtlety >>> gamma = 1 >>> gamma = 2 gamma int 2 int 1 ✘ Two separate integer objects. Python doesn’t change an integer’s value; Python replaces the integer. Python integers are “immutable”
  • 134.
    134 Names on theRHS — 1 >>> delta = alpha + 40 RHS 1. alpha 40+ function + int 40int 100 alpha int 140 2. 3.
  • 135.
    135 Names on theRHS — 2 >>> delta = alpha + 40 LHS 4. delta int 140
  • 136.
    136 Same name onboth sides — 0 delta int 140 Starting position >>> print(delta) 140
  • 137.
    137 Same name onboth sides — 1 >>> delta = delta + 10 RHS 1. delta 10+ function + int 10int 140 delta int 150 2. 3. 4.
  • 138.
    138 Same name onboth sides — 2 >>> delta = delta + 10 5. 6. LHS int 150 int 140delta RHS int 150 int 140delta RHS
  • 139.
    139 Same name onboth sides — 3 >>> delta = delta + 10 7. 8. LHS int 150delta int 150 int 140delta ✗ No longer used.
  • 140.
    140 “Syntactic sugar” thing +=10 thing = thing + 10 thing -= 10 thing = thing - 10 thing *= 10 thing = thing * 10 thing /= 10 thing = thing / 10 thing **= 10 thing = thing ** 10 thing %= 10 thing = thing % 10 is equivalent to
  • 141.
    141 Deleting a name― 1 >>> print(thing) Traceback (most recent call last): File "<stdin>", line 1, in <module> >>> thing = 1 >>> print(thing) 1 NameError: name 'thing' is not defined Unknown variable
  • 142.
    142 Deleting a name― 2 >>> print(thing) Traceback (most recent call last): File "<stdin>", line 1, in <module> >>> del thing >>> print(thing) 1 NameError: name 'thing' is not defined Unknown variable Known variable
  • 143.
    143 Progress Assignment Strictly right toleft += etc. “syntactic sugar” thing = thing + 10 thing = thing + 10 2nd 1st thing += 10 Deletion del thing
  • 144.
    144 Our first “real”program 1.414213562373095 $ Number? python3 sqrt.py 2.0 We have to write sqrt.py First, the maths. Then, the Python.
  • 145.
    145 Square root of2.0 by “bisection” “Interval of uncertainty” 0.0 too small for √2 2.0 too large for √2 0.0 < √2 < 2.0
  • 146.
    146 Square root of2.0 by bisection — 1 Mid-point: 1.0 (0.0 + 2.0) / 2.0 1.0 1.0**2 1.0
  • 147.
    147 Square root of2.0 by bisection — 2 1.0**2 < 2.0 1.0 < √2 < 2.0 so change lower bound midpoint √2 22 <
  • 148.
    148 Square root of2.0 by bisection — 3 Mid-point: 1.5 (1.0 + 2.0) / 2.0 1.5 1.5**2 2.25
  • 149.
    149 Square root of2.0 by bisection — 4 1.5**2 > 2.0 so change upper bound 1.0 < √2 < 1.5
  • 150.
    150 Square root of2.0 by bisection — 5 Mid-point: 1.25 (1.0 + 1.5) / 2.0 1.25 1.25**2 1.5625
  • 151.
    151 Square root of2.0 by bisection — 6 1.25**2 < 2.0 so change lower bound 1.25 < √2 < 1.5
  • 152.
    152 Square root of2.0 by bisection — 7 Mid-point: 1.375 (1.25 + 1.5) / 2.0 1.375 1.375**2 1.890625
  • 153.
    153 Square root of2.0 by bisection — 8 1.375**2 < 2.0 so change lower bound 1.375 < √2 < 1.5
  • 154.
    154 Exercise 6 1.375 <√2 < 1.5 One more iteration. Find the mid-point. Square it. Compare the square to 2.0. Do you change the lower or upper bound? 2 minutes
  • 155.
  • 156.
    156 And now usingPython! lower = 0.0 upper = 2.0 middle = (lower+upper)/2
  • 157.
    157 And now usingPython — 2 middle**2 < 2.0 True lower = middle print(lower, upper) 2.01.0
  • 158.
    158 And now usingPython — 3 middle = (lower+upper)/2 print( middle**2)middle, 2.251.5
  • 159.
    159 And now usingPython — 4 middle**2 < 2.0 False upper = middle print(lower, upper) 1.51.0
  • 160.
    160 And now usingPython — 5 middle = (lower+upper)/2 print( middle**2)middle, 1.56251.25
  • 161.
    161 And now usingPython — 6 middle**2 < 2.0 True lower = middle print(lower, upper) 1.51.25
  • 162.
    162 And now usingPython — 7 middle = (lower+upper)/2 print( middle**2)middle, 1.8906251.375
  • 163.
    163 And now usingPython — 8 middle**2 < 2.0 True lower = middle print(lower, upper) 1.51.375
  • 164.
    164 Looking at thePython code lower = 0.0 upper = 2.0 middle = (lower+upper)/2 print(middle, middle**2) middle**2 < 2.0 lower = middle upper = middle ?✔ ✘ print(lower, upper)
  • 165.
    165 Looking at thePython structures lower = 0.0 upper = 2.0 middle = (lower+upper)/2 print(middle, middle**2) middle**2 < 2.0 lower = middle upper = middle ?✔ ✘ print(lower, upper) Set up Loop Choice
  • 166.
    166 Looping Before Loop test Loop body After ✘✔ Should the loop run (again)? What is run each loop?
  • 167.
    167 Loop example: Countfrom 1 to 10 number = 1 number <= 10 print(number) number += 1 print('Done!') ✘ ✔ Before Loop test Loop body After ✘ ✔
  • 168.
    168 Loop example: Countfrom 1 to 10 number = 1 number <= 10 print(number) number += 1 print('Done!') ✘ ✔ number = 1 while print(number) number += 1 print('Done!') :number <= 10 ␣␣␣␣ ␣␣␣␣
  • 169.
    169 Loop test: Countfrom 1 to 10 number = 1 while print('Done!') :number <= 10 “while” keyword loop test colon print(number) number += 1 ␣␣␣␣ ␣␣␣␣
  • 170.
    170 Loop body: Countfrom 1 to 10 number = 1 while print('Done!') :number <= 10 loop body indentation print(number) number += 1 ␣␣␣␣ ␣␣␣␣
  • 171.
    171 number = 1 whilenumber <= 10 : print(number) number += 1 print('Done!') Loop example: Count from 1 to 10 while1.py $ 1 2 3 4 5 6 7 8 9 10 Done! python3 while1.py $
  • 172.
    172 Python’s use ofindentation number = 1 while number <= 10 : p ␣␣␣␣ ␣␣␣␣ print(number) number += 1 Four spaces’ indentation indicate a “block” of code. The block forms the repeated lines. The first unindented line marks the end of the block. rint('Done!')
  • 173.
  • 174.
    174 Other languages Shell C while ... do ␣␣␣␣... ␣␣␣␣... done while... { ␣␣␣␣... ␣␣␣␣... } do ... done { ... } Syntax Syntax ␣␣␣␣... ␣␣␣␣... Clarity Clarity
  • 175.
    175 Progress while ... :before while test : ␣␣␣␣action1 ␣␣␣␣action2 ␣␣␣␣action3 afterwards test to keep looping code blocks ␣␣␣␣indentation
  • 176.
    176 Exercise 7 5 minutes Foreach script: Predict what it will do. Run the script. Were you right? while2.py while3.py while4.py while5.py␣␣␣␣ ␣␣␣␣ ␣␣␣␣ To kill a running script: Ctrl C+ while6.py
  • 177.
    177 1.51.375 Back to oursquare root example 1.0 2.0 1.0 0.0 2.0 2.0 1.0 1.5 0.5 1.25 1.5 0.25 0.125 ×½ ×½ ×½ ×½ uncertainty 1.0×10–15 tolerance What we get What we want
  • 178.
    178 Keep looping while… ? tolerance>uncertainty while uncertainty > tolerance : ␣␣␣␣ ␣␣␣␣ ␣␣␣␣ ␣␣␣␣ Do stuff.
  • 179.
    179 Square root: theloop lower = 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) ? Set up Loop Choice
  • 180.
    180 Choosing middle**2 < 2.0 lower= middle upper = middle ?✔ ✘ Choice middle**2 < 2.0 True Falseor True False lower = middle upper = middle
  • 181.
    181 Simple example text =input('Number? ') number = int(text) if number % 2 == 0: print('Even number') else: print('Odd number') print('That was fun!') ifthenelse1.py $ Number? Even number That was fun python3 ifthenelse1.py $ Number? Odd number That was fun python3 ifthenelse1.py 8 7
  • 182.
    182 if…then… else… ―1 if else : ␣␣␣␣print('Even number') ␣␣␣␣upper = middle :number % 2 == 0 if keyword Test Colon print('That was fun!')
  • 183.
    183 if…then… else… ―2 if else : ␣␣␣␣ print('Even number') ␣␣␣␣upper = middle :number % 2 == 0 Run if test is True Indentation print('That was fun!')
  • 184.
    184 if…then… else… ―3 if else : ␣␣␣␣print('Even number') ␣␣␣␣ upper = middle :number % 2 == 0 else: keyword Run if test is False Indentation print('That was fun!')
  • 185.
    185 if…then… else… ―4 if else : ␣␣␣␣print('Even number') ␣␣␣␣ upper = middle :number % 2 == 0 Run afterwards regardless of test print('That was fun!')
  • 186.
    186 Our square rootexample middle = (lower + upper)/2 if else : print(lower, upper) ␣␣␣␣lower = middle ␣␣␣␣upper = middle Before :middle**2 < 2.0 After if… block
  • 187.
    187 Progress if ... :before if test : ␣␣␣␣action1 ␣␣␣␣action2 else: ␣␣␣␣action3 afterwards else: choice of two code blocks ␣␣␣␣indentation
  • 188.
    188 Exercise 8 5 minutes Foreach script: Predict what it will do. Run the script. Were you right? ifthenelse2.py ifthenelse3.py ifthenelse4.py ␣␣␣␣ ␣␣␣␣ ␣␣␣␣
  • 189.
    189 Back to ourexample lower = 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) if middle**2 < 2.0 : else : upper = middle lower = middle Doubly indented if starts indented
  • 190.
    190 Levels of indentation lower= 0.0 upper = 2.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) if middle**2 < 2.0 : else : upper = middle lower = middle ␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣ 4 spaces 8 spaces
  • 191.
    191 Trying it out tolerance= 1.0e-15 lower = 0.0 upper = 2.0 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 if middle**2 < 2.0: lower = middle else: upper = middle print(lower, upper) uncertainty = upper - lower sqrt1.py $ 1.0 2.0 1.0 1.5 1.25 1.5 1.375 1.5 1.375 1.4375 1.40625 1.4375 1.40625 1.421875 ... 1.414213... 1.414213... python3 sqrt1.py ☺
  • 192.
    192 Script for thesquare root of 2.0 lower = 0.0 tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance : middle = (lower + upper)/2 uncertainty = upper - lower print(lower, upper) upper = 2.0 if middle**2 < 2.0 : else : upper = middle lower = middle ␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣␣␣␣␣ ␣␣␣␣ ␣␣␣␣ √2.0 √2.0
  • 193.
    193 Input target text =input('Number? ') number = float(text) if middle**2 < number : …
  • 194.
    194 Initial bounds? x >1.0 1.0 < √x < x 1.0 > x 1.0 > √x > x lower = ? upper = ? if...then...else...
  • 195.
    195 Initial bounds if number< 1.0 : ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else : ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number
  • 196.
    196 Generic square rootscript? text = input('Number?␣') number = float(text) if number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number tolerance = 1.0e-15 uncertainty = upper - lower while uncertainty > tolerance: ␣␣␣␣middle = (lower+upper)/2.0 ␣␣␣␣if middle**2 < number: ␣␣␣␣␣␣␣␣lower = middle ␣␣␣␣else: ␣␣␣␣␣␣␣␣upper = middle ␣␣␣␣uncertainty = upper - lower print(lower, upper) User input Initialization Processing Output sqrt2.py
  • 197.
    197 exit()␣␣␣␣ Negative numbers? Need tocatch negative numbers if number < 0.0: ␣␣␣␣print('Number must be positive!') Quit immediately "else" is optional
  • 198.
    198 “Chained” tests text =input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number must be positive!') ␣␣␣␣exit() if number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number ... User input Input validation Initialization
  • 199.
    199 elif “Chained” tests ―syntactic sugar text = input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number must be positive!') ␣␣␣␣exit() number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number ... elif: “else if” sqrt3.py
  • 200.
    200 Without elif… text =input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number is negative.') else: ␣␣␣␣if number < 1.0: ␣␣␣␣␣␣␣␣print('Number is between zero and one.') ␣␣␣␣else: ␣␣␣␣␣␣␣␣if number < 2.0: ␣␣␣␣␣␣␣␣␣␣␣␣print('Number is between one and two.') ␣␣␣␣␣␣␣␣else: ␣␣␣␣␣␣␣␣␣␣␣␣if number < 3.0: ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣print('Number is between two and three.') ␣␣␣␣␣␣␣␣␣␣␣␣else: ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣print('Number is three or more.') Stacked clauses get unwieldy
  • 201.
    201 With elif… text =input('Number?␣') number = float(text) if number < 0.0: ␣␣␣␣print('Number is negative.') elif number < 1.0: ␣␣␣␣print('Number is between zero and one.') elif number < 2.0: ␣␣␣␣print('Number is between one and two.') elif number < 3.0: ␣␣␣␣print('Number is between two and three.') else: ␣␣␣␣print('Number is three or more.')
  • 202.
    202 Progress Nested structures if …: … elif … : … elif … : … else: … while … : if … : Chained tests Testing inputs to scripts exit()
  • 203.
    203 Exercise 9 10 minutes exercise9.py 1.Edit the square root script to catch negative numbers. Only attempt each part after you have the previous part working! 2. Edit the square root script to ask for the tolerance. 3. Edit the square root script to catch negative tolerances.
  • 204.
    204 Comments We have writtenour first real Python script What did it do? Why did it do it? Need to annotate the script
  • 205.
    205 Python comment character The“hash” character Lines starting with “#” are ignored Partial lines starting “#” are ignored Used for annotating scripts # a.k.a. “pound”, “number”, “sharp”
  • 206.
    206 Python commenting example #Script to calculate square roots by bisection # (c) Bob Dowling 2012. Licensed under GPL v3.0 text = input('Number?␣') number = float(text) # Need a real number # Test number for validity, # set initial bounds if OK. if number < 0.0: ␣␣␣␣print('Number must be non-negative!') ␣␣␣␣exit() elif number < 1.0: ␣␣␣␣lower = number ␣␣␣␣upper = 1.0 else: ␣␣␣␣lower = 1.0 ␣␣␣␣upper = number
  • 207.
    207 On a realUnix system… #!/usr/bin/python3 # Script to calculate square roots by bisection # (c) Bob Dowling 2012. Licensed under GPL v3.0 text = input('Number?␣') number = float(text) # Need a real number Magic line for executable files $ instead of fubar.py $ python3 fubar.py
  • 208.
  • 209.
    209 Exercise 10 2 minutes Commentyour square root script from exercise 9.
  • 210.
    210 Recap: Python typesso far Whole numbers Floating point numbers Text Booleans -127 3.141592653589793 'The cat sat on the mat.' True False Complex numbers (1.0 + 2.0j)
  • 211.
    211 Lists [ 'hydrogen', 'helium','lithium', 'beryllium', 'boron', …, 'thorium', 'protactinium', 'uranium' ] [ -3.141592653589793, -1.5707963267948966, 0.0, 1.5707963267948966, 3.141592653589793 ] [ 2, 3, 5, 7, 11, 13, 17, 19 ]
  • 212.
    212 What is alist? A sequence of values Individual value identified by position in the sequence The names of the elements “helium” is the name of the second element Values stored in order Atomic number order hydrogen, helium, lithium, beryllium, …, protactinium, uranium
  • 213.
    213 What is alist? A sequence of values Individual value identified by position in the sequence The prime numbers less than sixty 7 is the fourth prime Values stored in order Numerical order 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59
  • 214.
    214 Creating a listin Python >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> type(primes) <class 'list'> The whole list A Python type A literal list
  • 215.
    215 How Python presentslists [ ]1917,13,11,7,5,3 ,,2 Square brackets at the ends Commas between items
  • 216.
    216 Square brackets primes =[2, 3, 5, 7, 11] Literal list
  • 217.
    217 Python counts fromzero [ ]1917,13,11,7,5,3 ,,2 76543210“index” “value”
  • 218.
    218 Looking things upin a list >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> primes 2 >>> 17 ]0[ index primes ]6[ square brackets
  • 219.
    219 Square brackets primes =[2, 3, 5, 7, 11] Literal list primes[3] Index into list
  • 220.
    220 Counting from theend >>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> 19 primes ]-1[ getting at the last item -1-2-3-4-5-6-7-8
  • 221.
    221 Inside view ofa list list 8 int 19 … primes int 17 int 3 int 2 primes[0] primes[1] primes[6] primes[7]
  • 222.
    222 Length of alist primes list 8 >>> len 8 (primes) 0 7 Maximum index is 7 len() function: length of list
  • 223.
    223 Changing a valuein a list >>> data = ['alpha', 'beta', 'gamma'] >>> data[2] 'gamma' >>> data[2] = 'G' >>> data[2] 'G' >>> data ['alpha', 'beta', 'G'] The list Initial value Change value Check change Changed list
  • 224.
    224 Changing a valuein a list ― 1 >>> data = ['alpha', 'beta', 'gamma'] list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a Right to left
  • 225.
    225 Changing a valuein a list ― 2 >>> data = ['alpha', 'beta', 'gamma'] data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a Right to left
  • 226.
    226 Changing a valuein a list ― 3 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a str 1 G New value
  • 227.
    227 Changing a valuein a list ― 4 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a str 1 G No longer referenced
  • 228.
    228 Changing a valuein a list ― 5 >>> data[2] = 'G' Right to left data list 3 str 5 a l p h a str 4 b e t a str 1 G
  • 229.
    229 Removing an entryfrom a list ― 1 >>> del data[1] data list 3 str 5 a l p h a str 4 b e t a str 5 g a m m a data[0] data[1] data[2] ✗
  • 230.
    230 Removing an entryfrom a list ― 2 >>> del data[1] data list 2 str 5 a l p h a str 4 b e t a str 5 g a m m a data[0] data[1] No longer referenced
  • 231.
    231 Removing an entryfrom a list ― 3 >>> del data[1] data list 2 str 5 a l p h a str 5 g a m m a data[0] data[1]
  • 232.
    232 Running off theend list 8 int 19 … primes int 17 int 3 int 2 primes[8]
  • 233.
    233 Running off theend >>> len(primes) 8 >>> primes[7] 19 >>> primes[8] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range Type of error Description of error
  • 234.
    234 Running off theend >>> primes[8] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range Same type of error Similar description of error but with “assignment”
  • 235.
    235 Progress Lists index Count from zero Length Over-running [2,3, 5, 7, 11, 13, 17, 19] primes[4] primes[0] len(primes) primes[8] Deletion del primes[6]
  • 236.
    236 Exercise 11 5 minutes Trackwhat the value of numbers is at each stage of this sequence of instructions. numbers = [5, 7, 11, 13, 17, 19, 29, 31]>>> numbers[1] = 3>>> del numbers[3]>>> numbers[3] = 37>>> numbers[4] = numbers[5]>>> 1 2 3 4 5
  • 237.
    237 How can weadd to a list? list 8 int 19 … int 17 int 2 list 9 int 19 … int 17 int 2 int 23 ? Same list Extra item New length
  • 238.
    238 Appending to alist >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> primes >>> primes [2, 3, 5, 7, 11, 13, 17, 19, (23)append. The list is now updated ]23 A function built into a list
  • 239.
    239 primes.append() ? >>> primes(23)append. The list A connecting dot append() The value to append All lists have this function built in.
  • 240.
    240 “Methods” (arguments)object function. a functionthat has special access to the object’s data. Behaves just like a function
  • 241.
    241 Using the append()method >>> print(primes) [2, 3, 5, 7, 11, 13, 17, 19] >>> primes (23)append. >>> primes (29)append. >>> primes (31)append. >>> primes (37)append. >>> print(primes) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] The function doesn’t return any value. It modifies the list itself.
  • 242.
    242 Other methods onlists: reverse() >>> numbers = [4, 7, 5, 1] >>> numbers.reverse() >>> print(numbers) [1, 5, 7, 4] The function doesn’t return any value. It modifies the list itself.
  • 243.
    243 Other methods onlists: sort() >>> numbers = [4, 7, 5, 1] >>> numbers.sort() >>> print(numbers) [1, 4, 5, 7] Numerical order. The function does not return the sorted list. It sorts the list itself.
  • 244.
    244 Other methods onlists: sort() >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek.sort() >>> print(greek) ['alpha', 'beta', 'delta', 'gamma'] Alphabetical order of the words.
  • 245.
    245 Other methods onlists: insert() >>> greek = 'gamma',['alpha', 0 1 2 >>> greek.insert( 'delta'] Where to insert What to insert 'beta'1, ) >>> greek ['alpha', 'gamma', 'delta']'beta', 1 Displaced 0
  • 246.
    246 Other methods onlists: remove() >>> numbers = [7, 4, >>> numbers.remove >>> print(numbers) [7, 4, 7, 2, 5, 4]8, (8) 7, 2, 5, 4] c.f. del numbers[2] Value to remove Index to remove
  • 247.
    247 Other methods onlists: remove() >>> >>> numbers.remove >>> print(numbers) [7, (4) print(numbers) [7, 7, 2, 5,4, 4] 7, 2, 5, 4] Only the first instance is removed There are two instances of 4.
  • 248.
    248 What methods arethere? >>> help(numbers) Help on list object: class list(object) ... | append(...) | L.append(object) -- append object to end ... Pagination: ␣ B next page back one page Q quit
  • 249.
    249 Help on asingle method >>> help(numbers.append) Help on built-in function append: append(...) L.append(object) -- append object to end
  • 250.
    250 Sorting a listredux >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek.sort() >>> print(greek) ['alpha', 'beta', 'delta', 'gamma'] Recall: greek.sort() sorts the list “in place”.
  • 251.
    251 Sorting a listredux: “sorted()” >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> print(sorted(greek)) >>> print(greek) ['alpha', 'beta', 'gamma', 'delta'] sorted() function returns a sorted list… ['alpha', 'beta', 'delta', 'gamma'] …and leaves the list alone
  • 252.
    252 Adding to alist redux: “+” >>> primes [2, 3, 5, 7, 11, 13, 17, 19] >>> primes [2, 3, 5, 7, 11, 13, 17, 19, [23, 29, 31]+ 23, 29, 31] Concatenation operator List to add
  • 253.
    253 Concatenation >>> newlist >>> >>> primes =primes + [23, 29, 31] primes = primes + [23, 29, 31] Create a new list Update the list [23, 29, 31]+= Augmented assignment
  • 254.
    254 Creating lists fromtext ― 1 >>> list('Hello') ['H', 'e', 'l', 'l', 'o'] str 5 H e l l o list 5 str 1 H str 1 e str 1 l str 1 l str 1 o
  • 255.
    255 Creating lists fromtext ― 2 >>> 'Hello, world!' ['Hello,', 'world!'] list 2 H e l l o , ␣ w o r l d !13str str 6 H e l l o , str 6 w o r l d ! .split() Built in method Splits on spaces
  • 256.
  • 257.
  • 258.
    258 Is an itemin a list? ― 1 >>> odds = [3, 5, 7, 9] Does not include 2 >>> odds.remove(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Hard error list.remove(x): x not in list x must be in the list before it can be removed Try to remove 2 ✗
  • 259.
    259 Is an itemin a list? ― 2 >>> odds = [3, 5, 7, 9] >>> 2 in odds False >>> 3 in odds True >>> 2 not in odds True
  • 260.
    260 Precedence x**y x*yx/yx%y x+yx-y+x-x x==yx>yx>=yx!=y x<yx<=y not x x or yx and y First Last x not in y x in y The list now contains every operator we meet in this course.
  • 261.
    261 Safe removal if numberin numbers : numbers.remove(number) while number in numbers : numbers.remove(number) What’s the difference?
  • 262.
    262 Working through alist ― 1 e.g. Printing each element on a line ['The', 'cat', 'sat', 'on', 'the', 'mat.'] The cat sat on the mat.
  • 263.
    263 Working through alist ― 2 e.g. Adding the elements of a list [45, 76, -23, 90, 15] 203 What is the sum of an empty list? [] ?
  • 264.
    264 Working through alist ― 3 e.g. Squaring every number in a list [4, 7, -2, 9, 1] [16, 49, 4, 81, 1]
  • 265.
    265 The “for loop”― 1 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for ␣␣␣␣ :wordsinword print(word) name of list list A new Python looping construct print: What we want to do with the list items.
  • 266.
    266 The “for loop”― 2 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for ␣␣␣␣ :wordsinword print(word) keywords colon followed by an indented block
  • 267.
    267 word) The “for loop”― 3 words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for :wordsinword print( Defining the loop variable Using the loop variable ␣␣␣␣
  • 268.
    268 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ First loop
  • 269.
    269 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Second loop
  • 270.
    270 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Third loop
  • 271.
    271 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Fourth loop
  • 272.
    272 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Fifth loop
  • 273.
    273 Running the “forloop” list 6 str 3 T h e str 3 c a t str 3 s a t str 2 o n str 3 t h e str 4 m a t . words word for :wordsinword word)print(␣␣␣␣ Final loop
  • 274.
    274 The “for loop”for printing word) words ['The', 'cat', 'sat', 'on', 'the', 'mat.']= for :wordsinword print(␣␣␣␣ for1.py
  • 275.
    275 The “for loop”for adding numbers = [45, 76, -23, 90, 15] for :in total += total = 0 number numbers print(total) number Set up before the loop Processing in the loop Results after the loop ␣␣␣␣ for2.py
  • 276.
    276 The “for loop”for creating a new list numbers = [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers print(squares) Set up before the loop Processing in the loop Results after the loop number**2)␣␣␣␣ for3.py
  • 277.
    277 The loop variablepersists! numbers = [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers print( number**2)␣␣␣␣ )number Loop variable only meant for use in loop! But it persists!
  • 278.
    278 “for loop hygeine” numbers= [4, 7, -2, 9, 1] for :in squares.append( squares = [ ] number numbers del number**2)␣␣␣␣ number Delete it after use
  • 279.
    279 Progress Testing items inlists for loops 3 in [1,2,3,4] total = 0 for number in [1,2,3,4]: total += number del number True loop variables for number in [1,2,3,4]: total += number del number
  • 280.
    280 Exercise 13 5 minutes Whatdoes this print? numbers = [0, 1, 2, 3, 4, 5] total = 0 total_so_far = [] for number in numbers: total += number total_so_far.append(total) print(total_so_far)
  • 281.
    281 “Sort-of-lists” Python “magic”: Treat itlike a list and it will behave like a useful list What can “it” be?
  • 282.
    282 Strings as lists Recall: list('Hello')['H', 'e', 'l', 'l', 'o'] for letter in H e l l o print(letter) :'Hello' Gets turned into a list. for4.py
  • 283.
    283 Creating lists ofnumbers Built in to Python: range(start,limit) for number in print(number) :range(3,8) 3 4 5 6 7 8 not included
  • 284.
    284 ranges of numbers Notactually lists: >>> range(0,5) range(0,5) But close enough: >>> [0, 1, 2, 3, 4] list(range(0,5)) Treat it like a list and it will behave like a list
  • 285.
    285 Why not justa list? Most common use: for number in … range(0, 10000): Inefficient to make a huge list just for this “iterator” : anything that can be treated like a list list(iterator) Explicit list
  • 286.
    286 Ranges of numbersagain range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(3, 10) [3, 4, 5, 6, 7, 8, 9] range(3, 10, 2) [3, 5, 7, 9] via list() Start at 0 Every nth number range(10, 3, -2) [10, 8, 6, 4] Negative steps
  • 287.
    287 Indices of lists >>>primes = [ 2, 3, 5, 7, 11, 13, 17, 19] [ ]1917,13,11,7,5,3 ,,2 76543210 >>> len(primes) >>> list(range( 8 [0, 1, 2, 3, 4, 5, 6, 7] 8)) valid indices
  • 288.
    288 Direct value orvia the index? primes = [2, 3, 5, 7, 11, 13, 17, 19] for prime in primes: print(prime) for index in range(len(primes)): print(primes[index]) Equivalent Simpler
  • 289.
    289 Working with twolists: “dot product” list1 = [ 0.4]0.0,0.3, list2 = [ 0.6]0.5,0.2, ××× 0.240.00.06 + + 0.3 ∙
  • 290.
    290 Working with twolists: indices list1 = [0.3, 0.0, 0.4] list2 = [0.2, 0.5, 0.6] for index in sum = 0.0 print(sum) 0 1 2 indices :range(len(list1)) sum += list1[index]*list2[index] Dealing with values from both lists at the same time.
  • 291.
    291 iter 4 2 A little moreabout iterators ― 1 str 5 a l p h a str 4 b e t a str 5 g a m m a str 5 d e l t a >>> greek = ['alpha', 'beta', 'gamma', 'delta'] >>> greek_i = iter(greek) >>> next(greek_i) 'alpha' >>> next(greek_i) 'beta' Offset
  • 292.
    292 iter 4 ✗ A little moreabout iterators ― 2 str 5 a l p h a str 4 b e t a str 5 g a m m a str 5 d e l t a >>> next(greek_i) 'gamma' >>> next(greek_i) 'delta' >>> next(greek_i) Traceback (most recent call last): File "<stdin>", line 1, in <module> ✗StopIteration
  • 293.
    293 Progress Non-lists as lists “Iterators” range() Indicesof lists Parallel lists range(limit) range(start,limit) range(start,limit,step) range(3,7) [3,4,5,6] for letter in 'Hello': ... for index in range(len(things)): greek_i = iter(greek) next(greek_i)
  • 294.
    294 Exercise 14 5 minutes list1= [ 0.4]0.0,0.3, list2 = [ 0.6]0.5,0.2, -0.2-0.50.1 Complete exercise14.py 0.040.250.01 0.3++ Difference Square Add
  • 295.
    295 List “slices” primes =[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]>>> primes>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] primes[3]>>> 7 primes[3:9]>>> [7, 11, 13, 17, 19, 23] The list An item Part of the list
  • 296.
    296 Slices ― 1 primes= [2, 3, 5, 7, 11, 13, 17, 19, 29, 31] 3 9 [7,primes[3:9] Item 9 not included 23, 11, 13, 17, 19, 23] primes[ ]9:3 to from Up to but not including…
  • 297.
    297 Slices ― 2 primes7, 11, 13, 17, 19, 29, 31]23, primes[ ]9:3 [7, 11, 13, 17, 19, 23] [2, 3, 5, primes[ ]9: [2, 3, 5, 7, 11, 13, 17, 19, 23] primes[ ]:3 [7, 11, 13, 17, 19, 23, 29, 31] primes[ ]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
  • 298.
    298 Slices ― 3 primes7, 11, 13, 17, 19, 29, 31]23, primes[ ]9:3 [7, 11, 13, 17, 19, 23] [2, 3, 5, primes[ :9:3 [7, 13, 19 ]]2 primes[ :9:3 ]3 [7, 17 ]
  • 299.
    299 list 3 alphabet letters Copies and slices― 1 letters = ['a','b','c']>>> str 1 a str 1 b str 1 c alphabet = letters>>>
  • 300.
    300 list 3 alphabet letters Copies and slices― 2 letters[0] = 'A'>>> str 1 A str 1 b str 1 c print(alphabet)>>> ['A', 'b', 'c']
  • 301.
    301 letters alphabet list 3 Copies andslices ― 3 letters = ['a','b','c']>>> str 1 a str 1 b str 1 c alphabet = letters[:]>>> list 3 Slices are copies.
  • 302.
    302 Copies and slices― 4 letters[0] = 'A'>>> print(alphabet)>>> Slices are copies. ['a', 'b', 'c'] letters alphabet list 3 str 1 a str 1 b str 1 c list 3 str 1 A
  • 303.
  • 304.
    304 Exercise 15 3 minutes Predictwhat this Python will do. Then run it. Were you right? exercise15.py foo = [4, 6, 2, 7, 3, 1, 9, 4, 2, 7, 4, 6, 0, 2] bar = foo[3:12:3] bar[2] += foo[4] foo[0] = bar[1] print(bar)
  • 305.
    305 list 5 Diversion: Lists andstrings Text: “a string of characters” list() str 1 H str 1 e str 1 l str 1 l str 1 o str 5 H e l l o
  • 306.
    306 Indexing into strings 'Hello,world!'[0]>>> 'H' 'Hello, world!'[:4]>>> 'Hell' Simple indexing Slicing
  • 307.
    307 Strings are immutable 'Hello,world!'[0] = 'C'>>> Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
  • 308.
  • 309.
    309 Reading a textfile File name File object File contents 'treasure.txt' book 'TREASURE ISLAND' string file string “opening” the file reading from the file Finished with the file “closing” the file
  • 310.
    310 Opening a textfile >>> book )'r','treasure.txt'(open= Read-only [text] File name Python function Python file object “mode” book )'treasure.txt'(open= Read-only is the default
  • 311.
    311 Reading from afile object >>> line1 book= File object First line of file >>> line1 ' n'TREASURE ISLAND Includes the “end of line” next( ) “next line, please”
  • 312.
    312 File object areiterable >>> line2 next(book)= Second line of file >>> line2 'n' >>> line3 next(book)= >>> line3 'PART ONEn' A blank line Third line of file
  • 313.
    313 Closing the file >>>.close()book Method built in to file object Frees the file for other programs to write to it.
  • 314.
    314 The file object― 1 >>> book <_io.TextIOWrapper encoding='UTF-8'> name='treasure.txt' Text Input/Output File name Character encoding: how to represent letters as numbers.
  • 315.
    315 The file object― 2 file 29 treasure.txt UTF-8 TREASURE ISLAND↵ ↵ PART ONE↵ ↵ The Old Buccaneer↵ ↵ ☞ Pointer to the file on the file system “offset”: how far into the file we have read File name Text encoding
  • 316.
    316 Reading through afile Treat it like a list and it will behave like a list list(file_object) List of lines in the file >>> book = open('treasure.txt', 'r') >>> lines = list(book) >>> print(lines)
  • 317.
    317 Reading a filemoves the offset !>>> book = open('treasure.txt', 'r') >>> lines_a = list(book) >>> print(lines_a) >>> lines_b = list(book) >>> print(lines_b) [] Empty list Huge output…
  • 318.
    318 Reading a filemoves the offset >>> book >>> lines_a = >>> print(lines_a) >>> >>> print(lines_b) [] … File object starts with offset at start. = open('treasure.txt', 'r') Operation reads entire file from offset. list(book) lines_b = list(book) Offset changed to end of file. Operation reads entire file from offset. So there's nothing left to read.
  • 319.
    319 Resetting the offset >>>book >>> lines_a = >>> print(lines_a) >>> >>> … = open('treasure.txt', 'r') list(book) lines_b = list(book) >>> print(lines_b) book.seek(0) Set the offset explicitly
  • 320.
    320 Typical way toprocess a file book = open('treasure.txt', 'r') for line in book : … Treat it like a list…
  • 321.
    321 Example: lines ina file book = open('treasure.txt', 'r') n_lines = 0 for line in book : n_lines += 1 print(n_lines) Line count Read each line of the file Increment the count Print out the count book.close()
  • 322.
    322 Example: characters ina file book = open('treasure.txt', 'r') n_chars = 0 for line in book : n_chars print(n_chars) len(line) Number of characters on the line Increase the count by that many += book.close()
  • 323.
    323 Progress Opening file toread Reading file Closing file File offset book = open(filename, 'r') book.close() book.seek(0) for line in book: ...
  • 324.
    324 Exercise 16 5 minutes Completea script to count lines, words and characters of a file. exercise16.py
  • 325.
    325 Writing files File name Datato write File object 'treasure.txt' book 'TREASURE ISLAND' string file string “opening” the file writing to the file Finished with the file “closing” the file
  • 326.
    326 Opening a textfile for writing >>> output )'w','output.txt'(open= Open for writing [text] ! This will truncate an existing file
  • 327.
    327 Opening a textfile for appending >>> output )'a','output.txt'(open= Open for appending [text]
  • 328.
    328 Writing to afile object ― 1 >>> .writeoutput Method built in to file object File object (line1) Data being written6 Number of characters actually written >>> len(line1) 6
  • 329.
    329 Writing to afile object ― 2 >>> .writeoutput ('alpha Typical use: whole line. Includes “end of line” n') >>> .writeoutput ('be') >>> .writeoutput ('tan') Doesn’t have to be whole lines >>> .writeoutput ('gammandeltan') Can be multiple lines 6 2 3 12
  • 330.
    330 Closing the fileobject >>> .close()output Vital for written files
  • 331.
    331 Importance of closing Data“flushed” to disc on closure. Python script File object File system write “flush” !
  • 332.
    332 Importance of closingpromptly ! Files locked for other access open ['w'] open ['r'] ✗ (More a problem for Windows than Unix)
  • 333.
    333 Writing non-text values >>>output.write('Boo!n') Writing text (str) 5 >>> output.write(42) Writing non-text (int) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not int write() only accepts text ✗
  • 334.
    334 Writing non-text values >>>output.write( Convert to text: str() 2 >>> output.write('n') Explicit end-of-line 1 str(42)) Text formatting (later in the course) provides a more elegant solution.
  • 335.
    335 Progress Opening files forwriting Explicit ends of lines book = open(filename, 'w') book.write('n') Writing data book.write(str(data)) Writing text book.write(text) Closing the file is important book.close()
  • 336.
    336 Exercise 17 5 minutes Thescript exercise17.py prints a series of numbers ending in 1. Change the script to write to a file called output.txt instead of printing to the console.
  • 337.
  • 338.
    338 Functions we havemet print(line) open(filename, mode) range(from, to, stride) float(thing) int(thing) iter(list) str(thing) len(thing) type(thing) input(prompt) Not that many! “The Python Way”: If it is appropriate to an object, make it a method of that object. bool(thing) ord(char) chr(number) list(thing)
  • 339.
    339 Why write ourown functions? … read … test … fix … improve … add to … write Easier to … “Structured programming” … develop
  • 340.
    340 Defining a function (y1 ,y2 , y3 ) (x1 , x2 , x3 , x4 , x5 )= f Identify the inputs Identify the processing Identify the outputs
  • 341.
    341 A function todefine: total() Sum a list [1, 2, 3] [7, -4, 1, 6, 0] [ ] 6 10 0 “Edge case”
  • 342.
    342 Defining a Pythonfunction ― 1 def :( … )total colon inputs name of function define a function called …
  • 343.
    343 Defining a Pythonfunction ― 2 def total( ):numbers name for the input This name is internal to the function.
  • 344.
    344 Defining a Pythonfunction ― 3 def total(numbers): Colon followed by indentation ⇨
  • 345.
    345 Defining a Pythonfunction ― 4 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number “Body” of function
  • 346.
    346 Defining a Pythonfunction ― 4 def total( ):numbers sum_so_far for sum_so_far += number = 0 in numbers:number These variables exist only within the function’s body.
  • 347.
    347 Defining a Pythonfunction ― 5 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far This value is returned return this value
  • 348.
    348 Defining a Pythonfunction ― 6 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far And that’s it! Unindented after this
  • 349.
    349 Defining a Pythonfunction ― 7 And that’s it! All internal names cleaned up No need for del All internal names internal No need to avoid reusing names
  • 350.
    350 Using a Pythonfunction ― 1 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) The list we want to add up
  • 351.
    351 Using a Pythonfunction ― 2 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) The function we have just written
  • 352.
    352 Using a Pythonfunction ― 3 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) Printing out the answer
  • 353.
    353 Using a Pythonfunction ― 4 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) total1.py $ python3 total1.py 6 nb: Unix prompt
  • 354.
    354 Using a Pythonfunction ― 5 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far print(total([1, 2, 3])) print(total([7,-4,1,6,0])) print(total([])) total2.py $ python3 total2.py 6 10 0 Use the function multiple times
  • 355.
    355 Functions’ private names― 1 def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far data = [1, 2, 3] data_sum = total(data) print(data_sum) Function definition Main script
  • 356.
    356 Functions’ private names― 2 def total(numbers): ... total main script function “namespace”
  • 357.
    357 Functions’ private names― 3 data = [1, 2, 3] list 3 int 1 int 2 int 3 total data main script function
  • 358.
    358 Functions’ private names― 4 ... = total(data) total data main script list 3 int 1 int 2 int 3 def total(numbers): total numbers function
  • 359.
    359 Functions’ private names― 5 ... = total(data) total function data main script list 3 int 1 int 2 int 3 sum_so_far = 0 total numbers sum_so_far int 0
  • 360.
    360 Functions’ private names― 6 ... = total(data) total function data main script list 3 int 1 int 2 int 3 return sum_so_far total numbers sum_so_far int 6
  • 361.
    361 Functions’ private names― 7 data_sum = total(data) total function data main script list 3 int 1 int 2 int 3 return sum_so_far total numbers sum_so_far int 6 data_sum
  • 362.
    362 Functions’ private names― 8 data_sum = total(data) total function data main script list 3 int 1 int 2 int 3 int 6 data_sum
  • 363.
    363 Progress Functions “Structured programming” Defining afunction Returning a value def function(input): ... return output Private name spaces
  • 364.
    364 Exercise 18 5 minutes Editthe script exercise18.py. It currently defines and uses a function total() which adds the elements of a list. Change it to create a function product() which multiplies them. Three examples are included in the script. Running it should produce the following output: $ python3 exercise18.py 6 0 1
  • 365.
    365 Reminder about indices deftotal(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far def total(numbers): sum_so_far = 0 for index in range(len(numbers)): sum_so_far += numbers[index] return sum_so_far Equivalent total3.py total2.py
  • 366.
    366 Want a functionto add two lists of the same length term-by-term: Example of multiple inputs [1, 2, 3] [5, 7, 4] [6, 9, 7]& [10, -5] [15, 14] [25, 9]& [11, 11, -2, 2, 7][3, 7, 4, 1, 7] [8, 4, -6, 1, 0]& Two inputs
  • 367.
    367 Functions with multipleinputs def add_lists( sum_list = [] for sum sum_list.append(sum) return sum_list ):b_list,a_list :range(len(a_list))inindex b_list[index]+a_list[index]= Multiple inputs are separated by commas
  • 368.
    368 Functions with multipleinputs def add_lists( sum_list = [] for sum sum_list.append(sum) return sum_list ):b_list,a_list :range(len(a_list))inindex b_list[index]+a_list[index]= We have two lists… …so we have to use indexing
  • 369.
    369 Multiple outputs Write afunction to find minimum and maximum value in a list [1, 2, 3] [10, -5] [3, 7, 4, 1, 7] Two outputs 1 & -5 & 1 & 3 10 7
  • 370.
    370 Finding just theminimum def min_list(a_list): min_so_far = a_list[0] for if a < min_so_far: return :a_listina min_so_far = a min_so_far Returning a single value List cannot be empty! minlist.py
  • 371.
    371 Finding just themaximum def max_list(a_list): max_so_far = a_list[0] for if a > max_so_far: return :a_listina max_so_far = a max_so_far Returning a single value Only real change maxlist.py
  • 372.
    372 Finding both def minmax_list(a_list): max_so_far= a_list[0] for if a > max_so_far: return what? :a_listina max_so_far = a min_so_far = a_list[0] if a < min_so_far: min_so_far = a This is the real question
  • 373.
    373 Returning both def minmax_list(a_list): max_so_far= a_list[0] for if a > max_so_far: return :a_listina max_so_far = a min_so_far = a_list[0] if a < min_so_far: min_so_far = a min_so_far, max_so_far A pair of values minmaxlist.py
  • 374.
    374 “Tuples” e.g. min_value max_value, min_valueavg_value, max_value, Pair Triple Often written with parentheses: min_value max_value, min_value avg_value, max_value, ( ( ) ) Commas
  • 375.
    375 Using tuples toreturn values min_value max_value,return minimum In the function definitiondef … Using the function = minmax_list(values)maximum,
  • 376.
    376 Using tuples toattach names alpha =beta, 56,12 alpha = beta 56 12 = ( ) ( )
  • 377.
    377 Swapping values >>> alpha= 12 >>> beta = 56 >>> (alpha, beta) = (beta, alpha) >>> print(alpha) 56 >>> print(beta) 12 Swapping values
  • 378.
    378 Assignment works rightto left alpha = 12 beta = 56 (alpha, beta) = (beta, alpha) Stage 1: (beta, alpha) (56, 12) Stage 2: (alpha, 12)(56,=beta)
  • 379.
    379 Progress Multiple inputs Multiple outputs “Tuples” Simultaneousassignment def thing(in1 , in2 , in3 ): return (out1 , out2 , out3 ) (a, b, c) (a, b) = (a+b, a-b)
  • 380.
    380 Exercise 19 10 minutes Thescript exercise19.py is an answer to exercise 16. Edit it to: 1. define a function file_stats() that takes a file name and returns a triple (n_lines, n_words, n_chars) 2. use input() to read in a file name 3. use file_stats() with that file name 4. end with print(filename, file_stats(filename))
  • 381.
    381 Tuples and lists:similarities >>> >>>x = ['alpha','beta'] y = ('alpha','beta') >>> >>>x[1] y[1] 'beta' 'beta' >>> >>>len(x) len(y) 2 2 >>> (a, b) = (1, 2) >>> a 1 >>> [c, d] = [1, 2] >>> c 1 Indexing Length Simultaneous asignment
  • 382.
    382 Tuples and lists:differences >>> >>>x = ['alpha','beta'] y = ('alpha','beta') >>> >>>x[1] = 'B' y[1] = 'B' >>> x ['alpha','B'] TypeError: 'tuple' object does not support item assignment Lists are mutable Tuples are immutable
  • 383.
    383 Tuples and lists:philosophy Sequential: Concept of “next item” Lists Tuples Simultaneous: All items “at once” Best with all items of the same type Safe to have multiple types [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] ('Dowling', 'Bob', 50, 105.0, 'rjd4') Sequence of prime numbers Surname, forename, age, weight, user id Serial Parallel
  • 384.
    384 Functions we havewritten so far total(list) add_lists(list1 ,list2 ) minmax_list(list)
  • 385.
    385 Reusing functions withina script def square(limit): ... ... squares_a = square(34) ... five_squares = squares(5) ... squares_b = squares(56) ... One definition Multiple uses in the same file Easy!
  • 386.
    386 ... squares_a = squares(34) ... ... five_squares= squares(5) ... Reusing functions between scripts? def squares(limit): ... One definition How? ... squares_b = squares(56) ... Multiple uses in multiple files
  • 387.
    387 “Modules” def ... square(limit) five = squares(5) :... ... Definition Use Module: a container of functions def ... cubes(limit):
  • 388.
    388 def squares(limit): answer =[] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far text = input('Number? ') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) Modules: a worked example ― 1a sum_squares.py Starts empty utils.py
  • 389.
    389 Modules: a workedexample ― 1b $ python3 sum_squares.py Number? 5 30 $ python3 sum_squares.py Number? 7 91 = 0 + 1 + 4 + 9 + 16 = 0 + 1 + 4 + 9 + 16 + 25 + 36
  • 390.
    390 text = input('Number?') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) Modules: a worked example ― 2a def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py sum_squares.py Move the definitions into the other file.
  • 391.
    391 Modules: a workedexample ― 2b $ python3 sum_squares.py Number? 5 Traceback (most recent call last): File "sum_squares.py", line 4, in <module> squares_n = squares(number) NameError: name 'squares' is not defined Because we have (re)moved its definition.
  • 392.
    392 Modules: a workedexample ― 3a import utils text = input('Number? ') number = int(text) squares_n = squares(number) total_n = total(squares_n) print(total_n) def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py sum_squares.py import: Make a reference to the other file. import utils and not import utils.py
  • 393.
    393 Modules: a workedexample ― 3b $ python3 sum_squares.py Number? 5 Traceback (most recent call last): File "sum_squares.py", line 4, in <module> squares_n = squares(number) NameError: name 'squares' is not defined Still can’t find the function(s).
  • 394.
    394 Modules: a workedexample ― 4a import utils text = input('Number? ') number = int(text) squares_n = utils.squares(number) total_n = utils.total(squares_n) print(total_n) sum_squares.py utils.…: Identify the functions as coming from the module. squares() utils.squares() total() utils.total()
  • 395.
    395 Modules: a workedexample ― 4b $ python3 sum_squares.py Number? 5 30 $ python3 sum_squares.py Number? 7 91 Working again! ☺
  • 396.
    396 Progress Sharing functions betweenscripts “Modules” Importing modules Using functions from modules import module module.function()
  • 397.
    397 Exercise 20 5 minutes Thescript exercise20.py is an answer to exercise19. Move the function file_stats() from exercise19.py into utils.py and edit exercise19.py so that it still works.
  • 398.
    398 The Python philosophy math sys string Asmall core language … … plus lots of modules “Batteries included”
  • 399.
    399 Example: the “math”module >>> import >>> math. 1.4142135623730951 math Load in the “math” module. Run the sqrt() function… … from the math module. 2.0)sqrt(
  • 400.
    400 import module asalias >>> import math >>> math. 1.4142135623730951 >>> import math as >>> m 1.4142135623730951 sqrt(2.0) Too long to keep typing? m .sqrt(2.0) “Alias”
  • 401.
    401 Don’t do these >>>from math import sqrt >>> sqrt(2.0) 1.4142135623730951 >>> from math import * >>> sqrt(2.0) 1.4142135623730951 ! !! Much better to track the module.
  • 402.
    402 What system modulesare there? sys os string re csvargparse webbrowser math cmath colorsys pickle datetime email getpass glob html http io json logging random signal sqlite3 subprocess tempfile unicodedata unittest xml Python 3.2.3 comes with over 250 modules.
  • 403.
    403 “Batteries included” >>> help('modules') Pleasewait a moment while I gather a list of all available modules... CDROM binascii inspect shlex bdb importlib shelve Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". 263 modules Not quite this simple
  • 404.
    404 Additional downloadable modules numpy scipypsycopg2 MySQLdb cx_oracle ibm_db pyodbc Numerical PostgreSQL MySQL Oracle DB2 Databases pymssql SQL Servermatplotlib Graphics
  • 405.
    405 An example systemmodule: sys import sys print(sys.argv) argv.py $ python3 argv.py one two three ['argv.py', $ python3 argv.py 1 2 3 ['argv.py', '3']'2','1', Always strings 'three']'two','one', 0 1 2 3index
  • 406.
    406 sys.exit() exit() What wehave been using sys.exit What we should use(rc) “Return Code”: an integer 0: Everything was OK ≠0:Something went wrong
  • 407.
    407 An example systemmodule: sys But also… sys.path sys.version sys.modules sys.stdin sys.stdout sys.stderr Directories Python searches for modules Version of Python All modules currently imported Where input inputs from Where print prints to Where errors print to …and there’s more! sys.float_info All the floating point limits
  • 408.
    408 Modules in Python “Howdo I do X in Python?” “What’s the Python module to do X?” “Where do I find Python modules?”
  • 409.
    409 Finding modules Python: PyPI: Built-in modules PythonPackage Index SciPy: Scientific Python modules Search: “Python3 module for X”
  • 410.
    410 Help with modules >>>import math >>> help(math) NAME math DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. …
  • 411.
    411 Help with modulefunctions … FUNCTIONS acos(x) Return the arc cosine (measured in radians) of x. … >>> math.acos(1.0) 0.0
  • 412.
    412 Help with moduleconstants DATA e = 2.718281828459045 pi = 3.141592653589793 … … >>> math.pi 3.141592653589793
  • 413.
    413 Help for ourown modules? def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py >>> import utils >>> help(utils) NAME utils FUNCTIONS squares(limit) total(numbers) FILE /home/y550/utils.py Basic help already provided by Python
  • 414.
    414 Adding extra helptext def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer def total(numbers): sum_so_far = 0 for number in numbers: sum_so_far += number return sum_so_far utils.py >>> help(utils) NAME utils >>> import utils Fresh start"""Some utility functions from the Python for Absolute Beginners course """ FUNCTIONS squares(limit) total(numbers) DESCRIPTION Some utility functions from the Python for Absolute Beginners course
  • 415.
    415 Adding extra helptext to functions """Some utility functions from the Python for Absolute Beginners course """ def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer utils.py """Returns a list of squares from zero to limit**2. """ >>> help(utils) NAME utils DESCRIPTION ... >>> import utils Fresh start FUNCTIONS squares(limit) Returns a list of squares from zero to limit**2.
  • 416.
    416 Adding extra helptext to functions """Some utility functions from the Python for Absolute Beginners course """ def squares(limit): answer = [] for n in range(0,limit): answer.append(n**2) return answer utils.py """Returns a list of squares from zero to limit**2. """ >>> help(utils.squares) >>> import utils Fresh start squares(limit) Returns a list of squares from zero to limit**2.
  • 417.
    417 Progress Python a smalllanguage… …with many, many modules System modules Modules provide help Foreign modules Doc strings Functionality Module help(module) help(module.function)
  • 418.
    418 Exercise 21 5 minutes Addhelp text to your utils.py file.
  • 419.
    419 Recap: Lists &Indices list 3 Position 2 Position 1 Position 0 greek = ['alpha', 'beta', 'gamma'] str 5 a l p h a str 4 b e t a str 5 g a m m a greek[0] greek[1] greek[2]
  • 420.
    420 “Index in ―Value out” listindex value 1 greek 'beta'[1] Must be a number start at 0 no gaps in sequence
  • 421.
    421 Other “indices”: Strings? dictionaryEnglishSpanish 'cat' 'dog' 'mouse' 'gato' 'perro' 'ratón' dictionary
  • 422.
    422 Other “indices”: Tuples? dictionary(x,y) Objects (2,5) (4,5) 'Treasure' 'Fortress' dictionary
  • 423.
    423 Python “dictionaries” >>> en_to_es= { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['cat'] 'gato'
  • 424.
    424 Creating a dictionary— 1 'dog':'perro'{ },'cat':'gato' Curly brackets Comma 'cat' → 'gato' 'dog' → 'perro'
  • 425.
    425 Creating a dictionary— 2 'dog'{ },'cat' 'gato': 'perro': 'cat' 'gato' “key” “value” : :
  • 426.
    426 Using a dictionary— 1 >>> en_to_es = { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['cat'] 'gato' Creating the dictionary Using the dictionary
  • 427.
    427 Using a dictionary— 2 en_to_es ]'cat'[ 'gato' dictionary key value Square brackets
  • 428.
    428 Missing keys >>> en_to_es= { 'cat':'gato' , 'dog':'perro' } >>> en_to_es['dog'] 'perro' >>> en_to_es['mouse'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'mouse' Error message ✓ ✗
  • 429.
    429 Dictionaries are one-way ! >>>en_to_es = >>> en_to_es['dog'] 'perro' >>> en_to_es['perro'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: ✓ ✗ 'perro' Looking for a key { }'dog':,'cat': 'perro''gato'
  • 430.
    430 Adding to adictionary >>> en_to_es >>> en_to_es['mouse'] = 'ratón' >>> en_to_es['mouse'] 'ratón' = { 'cat':'gato' , 'dog':'perro' } Initial dictionary has no 'mouse' Adding 'mouse' to the dictionary
  • 431.
    431 Removing from adictionary >>> print(en_to_es) {'mouse': 'ratón', >>> del en_to_es[ >>> print(en_to_es) {'mouse': 'ratón', 'cat': 'gato'} 'cat': 'gato'}'dog': 'perro', ]'dog'
  • 432.
    432 Progress Dictionaries Key Value {key1 :value1 , key2 :value2 , key3 :value3 } dictionary[key] valueLooking up values dictionary[key] = valueSetting values del dictionary[key]Removing keys
  • 433.
    433 Exercise 22 5 minutes Completeexercise22.py to create an English to French dictionary. cat chat dog chien mouse souris snake serpent
  • 434.
    434 What’s in adictionary? ― 1 >>> en_to_es {'mouse': 'ratón', 'dog': 'perro', 'cat': 'gato'} >>> en_to_es.keys() dict_keys >>> en_to_es.values() dict_values Just treat them like lists Orders match (['mouse', 'dog', 'cat']) (['ratón', 'perro', 'gato']) (or convert them to lists)
  • 435.
    435 What’s in adictionary? ― 2 >>> en_to_es dict_items([('mouse', 'ratón'), ('dog', 'perro'), ('cat', 'gato')]) >>> for (english, spanish) in en_to_es.items(): ... print(spanish, english) ... ratón mouse perro dog gato cat Most useful method.items() (Key,Value) pairs/tuples
  • 436.
    436 What’s in adictionary? ― 3 >>> list [('mouse','ratón'), ('dog','perro'),('cat','gato')] Common simplification (en_to_es.items())
  • 437.
    437 Getting the listof keys dictionary list of keys list() {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1} ['on', 'the', 'sat', 'mat', 'cat']
  • 438.
    438 Is a keyin a dictionary? >>> en_to_es['snake'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'snake' Want to avoid this >>> 'snake' in en_to_es False We can test for it
  • 439.
    439 Example: Counting words― 1 words = ['the','cat','sat','on','the','mat'] counts = {'the':2,'cat':1,'sat':1,'on':1,'mat':1}
  • 440.
    440 Example: Counting words― 2 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: Do something Start with an empty dictionary Work through all the words
  • 441.
    441 Example: Counting words― 3 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: counts[word] += 1 ✗ This will not work counter1.py
  • 442.
    442 Why doesn’t itwork? counts = {'the':1, 'cat':1} counts['the'] += 1 counts['sat'] += 1 ✗ ✓ counts['the'] = + 1counts['the'] The key must already be in the dictionary. counts['sat'] = + 1counts['sat'] Key is not in the dictionary!
  • 443.
    443 Example: Counting words― 4 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: if word in counts: counts[word] += 1 else: Do something Need to add the key
  • 444.
    444 Example: Counting words― 5 words = ['the','cat','sat','on','the','mat'] counts = {} for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 counter2.py print(counts)
  • 445.
    445 Example: Counting words― 6 $ python3 counter2.py {'on': 1, 'the': 2, 'sat': 1, 'mat': 1, 'cat': 1} You cannot predict the order of the keys when a dictionary prints out. !
  • 446.
    446 Example: Counting words― 7 print(counts) items = list(dictionary.items()) items.sort() for (key, value) in items: print(key, value) ✗ Too ugly Better counter3.py
  • 447.
    447 Example: Counting words― 8 $ python3 counter3.py cat 1 mat 1 on 1 sat 1 the 2
  • 448.
    448 Progress Testing keys indictionaries Creating a list of keys if key in dictionary: ... keys = list(dictionary) Inspection methods dictionary.keys() dictionary.values() dictionary.items()
  • 449.
    449 Exercise 23 5 minutes Completeexercise23.py to write a script that reverses a dictionary. { { 'perro'}'dog':'gato','cat':'ratón','mouse': :'dog'}'perro''cat','gato':'mouse','ratón':
  • 450.
    450 Formatted output $ python3counter3.py cat 1 mat 1 sat 1 the 2 on 1 Ugly! cat mat on sat the 1 1 1 1 2 We want data nicely aligned
  • 451.
  • 452.
    452 String formatting ―1 >>> 'xxxA␣␣␣␣yyy' 'xxx{:5s}yyy'.format('A') ' ' yyy{:5s}xxx ' 'yyyA␣␣␣␣xxx {:5s} s ― substitute a string 5 ― pad to 5 spaces (left aligns by default)
  • 453.
    453 String formatting ―2 >>> 'xxxA␣␣␣␣yyy' 'xxx{:<5s}yyy'.format('A') ' ' yyy{:<5s}xxx ' 'yyyA␣␣␣␣xxx {:<5s} < ― align to the left (←)
  • 454.
    454 String formatting ―3 >>> 'xxx␣␣␣␣Ayyy' 'xxx{:>5s}yyy'.format('A') ' ' yyy{:>5s}xxx ' 'yyy␣␣␣␣Axxx {:>5s} > ― align to the right (→)
  • 455.
    455 Integer formatting ―1 >>> 'xxx␣␣123yyy' 'xxx{:5d}yyy'.format(123) ' ' yyy{:5d}xxx ' 'yyy␣␣123xxx {:5d} d ― substitute an integer 5 ― pad to 5 spaces (right aligns by default) (digits)
  • 456.
    456 Integer formatting ―2 >>> 'xxx␣␣123yyy' 'xxx{:>5d}yyy'.format(123) ' ' yyy{:>5d}xxx ' 'yyy␣␣123xxx {:>5d} > ― align to the right (→)
  • 457.
    457 Integer formatting ―3 >>> 'xxx␣␣123yyy' 'xxx{:>5d}yyy'.format(123) ' ' yyy{:<5d}xxx ' 'yyy123␣␣xxx {:<5d} < ― align to the left (←)
  • 458.
    458 Integer formatting ―4 >>> 'xxx00123yyy' 'xxx{:05d}yyy'.format(123) ' ' yyy{:05d}xxx ' 'yyy00123xxx {:05d} 0 ― pad with zeroes
  • 459.
    459 Integer formatting ―5 >>> 'xxx␣+123yyy' 'xxx{:+5d}yyy'.format(123) ' ' yyy{:+5d}xxx ' 'yyy␣+123xxx {:05d} + ― always show sign
  • 460.
    460 Integer formatting ―6 >>> 'xxx␣+0123yyy' 'xxx{:+05d}yyy'.format(123) ' ' yyy{:+05d}xxx ' 'yyy+0123xxx {:05d} + ― always show sign 0 ― pad with zeroes
  • 461.
    461 Integer formatting ―7 >>> 'xxx1,234yyy' 'xxx{:5,d}yyy'.format(1234) ' ' yyy{:5,d}xxx ' 'yyy1,234xxx {:5,d} , ― 1,000s
  • 462.
    462 Floating point formatting― 1 >>> 'xxx 1.20yyy' 'xxx{:5.2f}yyy'.format(1.2) ' ' yyy{:5.2f}xxx ' 'yyy␣1.20xxx {:5.2f} f ― substitute a float 5 ― 5 places in total .2 ― 2 places after the point
  • 463.
    463 Floating point formatting― 2 >>> 'xxx1.200000yyy' 'xxx{:f}yyy'.format(1.2) ' ' yyy{:f}xxx ' 'yyy1.200000xxx {:f} {:.6f}
  • 464.
    464 Ordering and repeats― 1 >>> 'X 'X )1.23123,'abc',X'.format({:f}X{:d}X{:s} X'1.230000X123Xabc 0 1 2 0 1 2 0 1 2 >>> 'X )1.23123,'abc',X'.format({2:f}X{1:d}X{0:s} 'X X'1.230000X123Xabc 0 1 2 0 1 2 Equivalent
  • 465.
    465 Ordering and repeats― 2 >>> 'X )1.23123,'abc',X'.format({2:f}X{1:d}X{0:s} 'X X1.230000 X123Xabc 0 12 0 1 2 ' >>> 'X )1.23123,'abc',X'.format(X{1:d}X{0:s} 'X X123Xabc 0 1 0 1 2 X' {1:d} 123 1
  • 466.
    466 Formatting in practice $python3 counter4.py cat mat on sat the 1 1 1 1 2 ... formatting = '{:3} {:1}' for (word, number) in items: print(formatting.format(word,number)) $
  • 467.
  • 468.
    468 Exercise 24 5 minutes Completeexercise24.py to format the output as shown: Joe 9 Samantha 45 Methuselah 969 [(Joe,9), (Samantha,45), (Methuselah,969)]
  • 469.
    469 And that's it!(And “it” is a lot!) Text Prompting Numbers Arithmetic Comparisons Booleans Variables Deleting names “while” loop “if” test Indented blocks Lists Indices Object methods Built-in help “for” loops “Treat it like a list…” Values direct/via index Reading files Writing files Functions “Structured programming” Tuples “for” loops Modules Dictionaries Formatting
  • 470.
    470 But wait! There’smore… Advanced topics: Self-paced introductions to modules Object-oriented programming in Python
  • 471.
    471 Text Prompting Numbers Arithmetic Comparisons Booleans Variables Deleting names “while” loop “if”test Indented blocks Lists Indices Object methods Built-in help “for” loops “Treat it like a list…” Values direct/via index Reading files Writing files Functions “Structured programming” Tuples “for” loops Modules Dictionaries Formatting Congratulations! Please don’t forget the feedback.