The document is an introductory guide to Python aimed at absolute beginners, covering essential programming concepts such as data types, input/output, and basic operations. It outlines a structured course with various topics spanning from basic commands to file handling and functions. Additionally, it provides resources and practices for effective learning and emphasizes the importance of detail and persistence in coding.
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
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
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 '''
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/
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
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!')
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
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:
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'>
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
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
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
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!
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.
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'>
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
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.
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
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
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!')
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.
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 ␣␣␣␣ ␣␣␣␣ ␣␣␣␣
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.')
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
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)
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
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]
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”
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.
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
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
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
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)
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
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)
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…
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
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
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: ...
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
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.
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
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
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
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
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
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()
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.
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
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?”
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)
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
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
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
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
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
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)) $
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