id
int64
0
25.6k
text
stringlengths
0
4.59k
10,200
def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far print(total([ ])printing out the answer
10,201
def total(numbers)sum_so_far for number in numberssum_so_far +number nbunix prompt python total py return sum_so_far print(total([ ])total py the file total py in your home directories contains exactly the code you see here
10,202
def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far print(total([ ])print(total([ ,- , , , ])print(total([])total py python total py use the function multiple times
10,203
def total(numbers)sum_so_far for number in numberssum_so_far +number function definition return sum_so_far data [ data_sum total(dataprint(data_summain script we will revisit the idea of names being private to functions and illustrate it with simple example suppose we had script that defined the total(function and had three lines of the main program as shown
10,204
def total(numbers)main script function total "namespace as python interprets the function it starts by adding name total to the set of names the script knows about and attaches that name to wherever the script' definition is in memory the name for this collection of names is the script' "namespace
10,205
data [ main script function total data list int int int then python interprets the first of the following three lines this establishes list of three integers and attaches name to it in the script' namespace
10,206
total(datadef total(numbers)total numbers main script function total data list int int int the next line calls the function as ever with assignment lines we start with the right hand side the rhs calls the function total with argument data when we call the function separate namespace is created for it within the definition of the function the name "numbersis used for the list as resultthe name "numbersis established in the function' namespace this name is attached to the same python object as the name "datain the script' namespace
10,207
total(datasum_so_far total sum_so_far int numbers main script function total data list int int int nextpython starts to execute the function' body the first line in the body defines name sum_so_far and attaches it to value (integerbecause this name appears in the function body it is established in the function' namespace
10,208
total(datareturn sum_so_far total sum_so_far int numbers main script function total data list int int int by the end of the script' execution the name sum_so_far in the script' namespace is attached to the value (integerit is this value that is returned
10,209
data_sum total(datareturn sum_so_far total sum_so_far int numbers main script function total data data_sum list int int int we now turn to the left hand side of the line in the main script this establishes name data_sum to attach to the value returned from the function call the name is defined in the main body fo the script and so is created in the script' namespace the name is attached to the value (integerthat was created by the function
10,210
data_sum total(dataint main script function total data data_sum list int int int now that python is done with the function garbage collection moves in and erases all trace of it its namespace is deletedleaving only the names defined in the main script' namespace
10,211
functions "structured programmingdefining function def function(input)returning value return output private name spaces
10,212
edit the script exercise py it currently defines and uses function total(which adds the elements of list change it to create function product(which multiplies them three examples are included in the script running it should produce the following outputpython exercise py minutes
10,213
def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far total py equivalent def total(numbers)sum_so_far for index in range(len(numbers))sum_so_far +numbers[indexreturn sum_so_far total py let' quickly remind ourselves about how we can uses indices for lists rather than values from lists directly we found this particularly useful when we were traversing more than one list at once
10,214
want function to add two lists of the same length term-by-term[ [ [ [ - [ [ [ [ - [ - two inputs so how do we build functions that take in more than one input at once
10,215
multiple inputs are separated by commas def add_lists(a_listb_list)sum_list [for index in range(len(a_list))sum a_list[indexb_list[indexsum_list append(sumreturn sum_list the python syntax for multiple inputs is much the same as it is for mathemtical functionwe separate the inputs by commas
10,216
we have two lists def add_lists(a_listb_list)sum_list [so we have to use indexing for index in range(len(a_list))sum a_list[indexb_list[indexsum_list append(sumreturn sum_list note that functions that take in more than one list typically need to use indices
10,217
write function to find minimum and maximum value in list [ [ - - [ two outputs but what if we want to return multiple valueswe can write function that determines the minimum value in listand we can write function that returns the maximum what do we do if we want to find both
10,218
def min_list(a_list)min_so_far a_list[ minlist py list cannot be emptyfor in a_list if min_so_farmin_so_far return min_so_far returning single value so here' the function that determines the minimum value in list
10,219
def max_list(a_list)maxlist py max_so_far a_list[ for in a_list if max_so_farmax_so_far return max_so_far only real change returning single value and just the maximum
10,220
def minmax_list(a_list)min_so_far a_list[ max_so_far a_list[ for in a_list if min_so_farmin_so_far if max_so_farmax_so_far return what this is the real question combining the bodies of these two functions is quite straightforward but what do we return
10,221
def minmax_list(a_list)minmaxlist py min_so_far a_list[ max_so_far a_list[ for in a_list if min_so_farmin_so_far if max_so_farmax_so_far return min_so_farmax_so_far pair of values two return two values we simply put them both after the return statement separated by commajust as we would have done with the inputs
10,222
min_valuemax_value pair min_valueavg_valuemax_value triple commas often written with parentheses(min_valuemax_value(min_valueavg_valuemax_value these sets of values separated by commas (but not in square brackets to make listare called "tuplesin python sometimes they are written with round brackets around them to make it clearer that they come together but it' the comma that is the active ingredient making them tuplenot the brackets
10,223
def return in the function definition min_value max_value using the function minimum maximum minmax_list(values if we return pair of values in tuplewe can also attach pair of names to them as tuple too
10,224
alpha (alpha beta beta we can do this outside the context of functions returning valuesof course we can do it anywhere
10,225
alpha beta (alphabeta(betaalphaswapping values print(alpha print(beta because the entire right hand side is evaluated before the left hand side is considered this lets us use tuples for some particularly useful tricks perhaps the most useful is swapping two values
10,226
alpha beta (alphabeta(betaalphastage (betaalphastage (alphabeta( ( the values associated with the names are evaluated first then the names get reattached to those valuesregardless of what names they might have had before
10,227
multiple inputs def thing(in in in )multiple outputs return (out out out "tuples(abcsimultaneous assignment (ab( +ba-
10,228
the script exercise py is an answer to exercise edit it to define function file_stats(that takes file name and returns triple (n_linesn_wordsn_chars use input(to read in file name use file_stats(with that file name end with print(filenamefile_stats(filename) minutes
10,229
['alpha','beta' ('alpha','beta' [ 'betay[ len( indexing 'betalen(ylength (ab( simultaneous asignment [cd[ now that we have seen how tuples work we should take moment to observe that they are very much like lists so why don' we just use liststhere are very many properties that lists and tuples share
10,230
['alpha','beta' ('alpha','beta' [ 'by[ 'bx typeerror'tupleobject does not support item assignment ['alpha',' 'lists are mutable tuples are immutable but there is one critical difference like stringstuples are immutable
10,231
lists tuples sequentialconcept of "next itemsimultaneousall items "at oncebest with all items of the same type safe to have multiple types serial parallel [ ('dowling''bob' 'rjd 'sequence of prime numbers surnameforenameageweightuser id philosophicallyit is appropriate to use lists where there is sequence of items or where you need mutability tuples are more appropriate for circumstances where you think about all the items at once because of thistuples are appropriate where you want to join together collection of parameters of different types into single object
10,232
total(listadd_lists(list ,list minmax_list(list to date we have written small number of functions ourselves once we become serious python programmers using the computer for our day job then we would expect to write many more
10,233
def square(limit)one definition squares_a square( five_squares squares( multiple uses in the same file squares_b squares( easy within script reusing function is easy we simply call the function whenever we want it
10,234
def squares(limit)one definition squares_a squares( multiple uses in multiple files five_squares squares( squares_b squares( how but what happens if we want to use function in more than one script
10,235
def square(limit)five squares( def cubes(limit)definition use modulea container of functions python has mechanism to assist with this called "modulesa module is collection of functions (and other materialwhich can then be imported into script and used within that script if we can write our own module with our own functions then we can import them into our own scripts
10,236
utils py starts empty def squares(limit)answer [for in range( ,limit)answer append( ** return answer def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far text input('number'number int(textsquares_n squares(numbertotal_n total(squares_nprint(total_nsum_squares py we will start with file called sum_squares py which uses two functions to add up the squares of numbers from zero to some limit we want to transfer those function definitions into different file which we will call utils py (which starts emptybut still be able to use them in our original file
10,237
python sum_squares py number python sum_squares py number just to prove ' not fibbinghere it is working before we move anything about
10,238
def squares(limit)answer [for in range( ,limit)answer append( ** return answer def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far utils py text input('number'number int(textsquares_n squares(numbertotal_n total(squares_nprint(total_nsum_squares py move the definitions into the other file using the text editor we move the definitions from sum_squares py to utils py
10,239
python sum_squares py number traceback (most recent call last)file "sum_squares py"line in squares_n squares(numbernameerrorname 'squaresis not defined because we have (re)moved its definition unsurprisinglythis breaks sum_squares py
10,240
def squares(limit)answer [for in range( ,limit)answer append( ** return answer def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far utils py import utils and not import utils py import utils text input('number'number int(textsquares_n squares(numbertotal_n total(squares_nprint(total_nsum_squares py importmake reference to the other file we need to import the functioned defined in utils py into sum_squares py firstwe add the instruction "import utilsto the top of the stm_squares py file note that we import "utils"not "utils py
10,241
python sum_squares py number traceback (most recent call last)file "sum_squares py"line in squares_n squares(numbernameerrorname 'squaresis not defined still can' find the function( on its own this is not sufficient
10,242
import utils squares(utils squares(total(text input('number'number int(textsquares_n utils squares(numbertotal_n utils total(squares_nprint(total_nutils total(sum_squares py utils identify the functions as coming from the module we have to indicate to python that these functions it is looking for in sum_squares py come from the utils module to do this we include "utils at the start of their names
10,243
python sum_squares py number python sum_squares py number working again and now it works
10,244
sharing functions between scripts "modulesimporting modules import module using functions from modules module function(
10,245
the script exercise py is an answer to exercise move the function file_stats(from exercise py into utils py and edit exercise py so that it still works minutes
10,246
small core language plus lots of modules math sys "batteries includedstring we have met the majority of the python language alreadybut obviously python has facilities to do much more than we have seen so far the trick is that python comes with large number of modules of its own which have functions for performing no end of useful things this philosophy is called "batteries includedyou probably already have the module you need to do your specialist application
10,247
import math load in the "mathmodule run the sqrt(function math sqrt( from the math module let' see an example of an "included batteryat the very start of this course we write ourselves square root program now let' see what python offers as an alternative we import the "mathmodule (no trailing " "this is the american spelling in the math module is sqrt(function we can access this as math sqrt(most of the fundamental mathematical operations can be found in the math mowe will see how to find out exactly what is in module in few slidestime
10,248
import math too long to keep typingmath sqrt( import math as "aliasm sqrt( there are those who object to typing if "mathis too long then we can use an aliasing trick to give the module shorter name (the problem is rarely with math there is built-in module called "multiprocessingthough which might get tiresome
10,249
from math import sqrt sqrt( much better to track the module from math import sqrt( ! python does permit you to do slightly more than that you can suppress the name of the module altogether you are beginners so please take it from an old hand on trust that this turns out to be very bad idea you want to keep track of where your functions came from
10,250
python comes with over modules glob math argparse csv io cmath datetime html os random getpass json signal colorsys logging re subprocess email pickle string sys http sqlite unicodedata tempfile webbrowser unittest xml there are many modules that come with python
10,251
help('modules'please wait moment while gather list of all available modules cdrom binascii inspect shlex modules bdb importlib shelve enter any module name to get more help ortype "modules spamto search for modules whose descriptions contain the word "spamnot quite this simple to find out exactly what modules come with your version of python ask the help system word of warningthough the text at the bottom "enter any module name is not quite right if you give the help(command with no argument then you are dropped into an interactive help system there you can type the name of module or type "modules spam"etc help(welcome to python this is the online help utility helpmodules subprocess here is list of matching modules name to get more help enter any module subprocess subprocess subprocesses with accessible / streams helpquit
10,252
numerical databases numpy pyodbc scipy psycopg postgresql mysqldb mysql cx_oracle oracle graphics ibm_db db matplotlib pymssql sql server butof coursethere' never the particular module you want there are modules provided by people who want python to interoperate with whatever it is they are offering there are three sets of additional modules that you may end up needing to know about the numerical and scientific world has collection of modules called numerical python ("numpy"and "scientific python("scipy"which contain enormous amounts of useful functions and types for numerical processing every database under the sun offers module to let python access it finally there is module to offer very powerful graphics for data visualisation and presentation
10,253
import sys python argv py one two three print(sys argv['argv py''one''two''three'index argv py python argv py ['argv py'' '' '' 'always strings we will take brief look at another commonly used module to illustrate some of the things python has hidden away in its standard set the "sysmodule contains many systems- things for exampleit contains list called sys argv which contains the argument values passed on the command line when the script was launched note two things that item zero in this list is always the name of the script itself the items are always strings
10,254
exit(what we have been using sys exit(rcwhat we should use "return code"an integer everything was ok something went wrong also tucked away in the sys module is the sys exit(function up to this point we have been using the exit(function to quit our scripts early however this function is something of filthy hack and sys exit(provides superior quitting and an extra facility we will be able to make use of the sys exit(function takes an integer argument this is the program' "return codewhich is very short message back to the operating system to indicate whether the program completed successfully or not return code of means "successa non-zero return code means failure some programs use different non-zero codes for different failures but many (most?simply use value of to mean "something went wrongif your script simply stops because it reached the end then python does an automatic sys exit(
10,255
but also sys modules all modules currently imported sys path directories python searches for modules sys version version of python sys stdin where input inputs from sys stdout where print prints to sys stderr where errors print to sys float_info all the floating point limits and there' moreand there' plenty more
10,256
"how do do in python?"what' the python module to do ?"where do find python modules? so the python philosophy places lot of functionality into its modules this means that we have to be able to find modules and know what they can do
10,257
pythonbuilt-in modules scipyscientific python modules pypipython package index search"python module for some useful urlsthis contains the list of all the "batteries includedmodules that come with python for each module it links through to their documentation scientific python contains very many subject-specific modules for python most depend on the numerical python module numpy (do check for python packagesthis is the semi-official dumping ground for everything else and for everything else there' google (who are big python usersby the way
10,258
import math help(mathname math description this module is always available it provides access to the mathematical functions defined by the standard promised information on how to find out what is in module here it is once module has been imported you can ask it for help
10,259
functions acos(xreturn the arc cosine (measured in radiansof math acos( the help will always include information on every function in the module
10,260
data pi math pi and every data item
10,261
def squares(limit)answer [for in range( ,limit)answer append( ** return answer def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far utils py basic help already provided by python import utils help(utilsname utils functions squares(limittotal(numbersfile /home/ /utils py what help can we get from our own moduleby now you should have utils py file with some functions of your own in it the help simply lists the functions the module contains and the file it is defined in
10,262
"""some utility functions from the python for absolute beginners course ""import utils def squares(limit)answer [for in range( ,limit)answer append( ** return answer name utils def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far fresh start help(utilsdescription some utility functions from the python for absolute beginners course functions squares(limit utils py total(numbersbut we can do better than that if we simply put python string (typically in long text triple quotesat the top of the file before any used python (but after comments is finethen this becomes the description text in the help noteyou need to restart python and re-import the module to see changes
10,263
"""some utility functions from the python for absolute beginners course ""import utils def squares(limit)"""returns list of squares from zero to limit** ""answer [for in range( ,limit)answer append( ** return answer name utils fresh start help(utilsdescription functions squares(limitreturns list of squares from zero to limit** utils py if we put text immediately after def line and before the body of the function it becomes the help text for that functionboth in the module-as-awhole help text
10,264
fresh start """some utility functions from the python for absolute beginners course ""import utils def squares(limit)"""returns list of squares from zero to limit** ""answer [for in range( ,limit)answer append( ** return answer squares(limitreturns list of squares from zero to limit** help(utils squares utils py and in the function-specific help text
10,265
python small language functionality module with manymany modules system modules foreign modules modules provide help help(moduledoc strings help(module function
10,266
add help text to your utils py file minutes
10,267
greek ['alpha''beta''gamma'list str greek[ str greek[ str greek[ position position position we have one last python type to learn about to give it some contextwe will recap the list type that we have spent so much time using list is basically an ordered sequence of values the position in that sequence is known as the index
10,268
must be number index list value greek[ 'betastart at no gaps in sequence if we now forget about the internals of listthoughwe can think of it as "some sort of python objectthat takes in number (the indexand spits out value
10,269
english dictionary 'cat'dog'mousespanish 'gatodictionary 'perro'raton can we generalise on this idea by moving away from the input (the indexneeding to be numbercan we model dictionary where we take in string ( word in englishsayand give out different string (the corresponding word in spanishsay(notethe author is fully aware that translation is not as simple as this this is just toy example
10,270
(xy( , ( , dictionary dictionary objects 'treasure'fortress orperhapspairs of numbers ( ,yin and items on map out
10,271
en_to_es 'cat':'gato'dog':'perroen_to_es['cat''gato python does have exactly such general purpose mapper which it calls "dict"short for "dictionaryhere is the python for establishing (very smallenglish to spanish dictionary that knows about two words we also see the python for looking up word in the dictionary we will review this syntax in some detail
10,272
curly brackets comma 'cat':'gato'dog':'perro'cat'gato'dog'perro first we will look at creating dictionary in the same way that we can create list with square bracketswe can create dictionary with curly ones each item in dictionary is pair of values separated by colo they are separated by commas
10,273
'cat'gato'cat':'gato'dog':'perro"key"value the pairs of items separated by colons are known as the "keyand "valuethe key is what you put in (the english word in this examplethat you look up in the dictionary and the value is what you get out (the translation into spanish in this example
10,274
en_to_es 'cat':'gato'dog':'perrocreating the dictionary en_to_es['cat'using the dictionary 'gato now we have seen how to create (smalldictionary we should look at how to use it
10,275
square brackets en_to_es'cat'gatodictionary value key to look something up in dictionary we pass it to the dictionary in exactly the same way as we passed the index to listin square brackets curly brackets are just for creating dictionaryafter that itsquare brackets again
10,276
en_to_es 'cat':'gato'dog':'perroen_to_es['dog''perroen_to_es['mouse'traceback (most recent call last)file ""line in keyerror'mouseerror message the equivalent to shooting off the end of list is asking for key that' not in dictionary
10,277
en_to_es 'cat':'gato'dog':'perroen_to_es['dog''perroen_to_es['perro'traceback (most recent call last)file ""line in keyerror'perro looking for key also note that dictionaries are one-way
10,278
en_to_es 'cat':'gato'dog':'perroinitial dictionary has no 'mouseen_to_es['mouse''ratonadding 'mouseto the dictionary en_to_es['mouse''raton adding key-value pairs to dictionary is lot easier than it is with lists with lists we needed to append on the end of list with dictionariesbecause there is no inherent orderwe can simply define them with simple expression on the left hand side
10,279
print(en_to_es{'mouse''raton''dog''perro''cat''gato'del en_to_es['dog'print(en_to_es{'mouse''raton''cat''gato' we can use del to remove from dictionary just as we did with lists
10,280
dictionaries key value key :value key :value key :value looking up values dictionary[keysetting values dictionary[keyvalue removing keys del dictionary[keyvalue
10,281
complete exercise py to create an english to french dictionary cat chat dog chien mouse souris snake serpent minutes
10,282
en_to_es {'mouse''raton''dog''perro''cat''gato'en_to_es keys(dict_keys(['mouse''dog''cat']orders match en_to_es values(dict_values(['raton''perro''gato']just treat them like lists (or convert them to lists to date we have created our own dictionaries if we are handed one how do we find out what keys and values are in itdictionaries support two methods which return the sort-of-lists of the keys and values we mention them here only for completeness don' forget that you can always convert sort-of-list into list with the list(function
10,283
en_to_es items(most useful method dict_items([('mouse''raton')('dog''perro')('cat''gato')](key,valuepairs/tuples for (englishspanishin en_to_es items()print(spanishenglishraton mouse perro dog gato cat by far the best way to get at the contents of dictionary is to use the items(method which generates sort-of-list of the key-value pairs as tuples running for loop over this list is the easiest way to process the contents of directory
10,284
common simplification list(en_to_es items()[('mouse','raton')('dog','perro'),('cat','gato') don' be afraid to convert it explicitly into list unless you dictionary is huge you won' see any problem with this
10,285
dictionary list(list of keys {'the' 'cat' 'sat' 'on' 'mat' ['on''the''sat''mat''cat' unfortunately when you convert dictionary directly into list you get the list of keys not the list of )(key,valuepairs this is shame but is compromise for back compatibility with previous versions
10,286
en_to_es['snake'traceback (most recent call last)file ""line in keyerror'snakewant to avoid this 'snakein en_to_es false we can test for it because of this conversion to the list of keys we can ask if key is in dictionary using the in keyword without having to know its corresponding value
10,287
words ['the','cat','sat','on','the','mat'counts {'the': ,'cat': ,'sat': ,'on': ,'mat': let' have serious worked example we might be given list of words and want to count the words by how many times they appear in the list
10,288
words ['the','cat','sat','on','the','mat'counts {start with an empty dictionary for word in wordswork through all the words do something we start by creating an empty dictionary it' empty because we haven' read any words yet then we loop through the list of words using standard for loop for each word we have to do something to increment the count in the dictionary
10,289
words ['the','cat','sat','on','the','mat'counts {for word in wordscounts[word+ this will not work counter py unfortunately simply increment of the value in the dictionary isn' enough
10,290
counts {'the': 'cat': the key must already be in the dictionary counts['the'+ counts['the'counts['the' counts['sat'+ key is not in the dictionarycounts['sat'counts['sat' we cannot increment value that isn' there until the program meets word for the first time it has no entry in the dictionaryand certainly not an entry with numerical value
10,291
words ['the','cat','sat','on','the','mat'counts {for word in wordsif word in countscounts[word+ elsedo something need to add the key so we have to test to see if the word is already in the dictionary to increment it if it is there and to do something else if it is not note how we use the "if key in dictionarytest
10,292
words ['the','cat','sat','on','the','mat'counts {for word in wordsif word in countscounts[word+ elsecounts[word counter py print(countsthat something else is to create it with its initial value of (because we have met the word once now
10,293
python counter py {'on' 'the' 'sat' 'mat' 'cat' you cannot predict the order of the keys when dictionary prints out dictionaries are unordered entities you cannot predict the order that the keys will appear when you print dictionary or step through its keys
10,294
print(countstoo ugly items list(dictionary items()better items sort(for (keyvaluein itemsprint(keyvaluecounter py simply printing dictionary gives ugly output we can pull out the (key,valuepairs and print them individually if we want notice the use of pulling out the itemsconverting them into list and then sorting them
10,295
python counter py cat mat on sat the
10,296
inspection methods dictionary keys(dictionary values(dictionary items(testing keys in dictionaries if key in dictionarycreating list of keys keys list(dictionary
10,297
complete exercise py to write script that reverses dictionary {'mouse':'raton''cat':'gato''dog':'perro'{'raton':'mouse''gato':'cat''perro':'dog' minutes
10,298
python counter py cat mat on sat the uglycat mat on sat the we want data nicely aligned we have one last topic to cover the output from our word counter is not as pretty as it might be the last topic we will cover is python text formatting full details of the formatting system can be found online at docs python org/py /library/string html#formatspec
10,299
'xxx{}yyy{}zzzformat(' ' 'xxxayyy zzz'xxx{}yyy{}zzz'xxxayyy zzz in python the string type has method called format(which takes arguments and returns another string which is the original with the method' arguments inserted into it in certain places those places are marked with curly brackets in the string curly brackets are otherwise quite normal characters it' only the format(method that cares about them in its simplest formthe format(method replaces each pair of curly brackets with the corresponding argument