id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,100 | primes [ concatenation operator list to add primes [ [ the list method we saw first appended single item to the end of list what happens if we want to add whole list of items at the endin this regardlists are like strings the "+operator performs concatenation and creates new list which is one concatenated after the other |
10,101 | create new list newlist primes [ update the list primes primes [ augmented assignment primes +[ we can use this to update list in place note that the augmented assignment operator "+=also works and is more than syntactic sugar this time it is actually more efficient than the long hand version because it updates the list in place rather than creating new one |
10,102 | list('hello'[' '' '' '' '' ' str str str str list str str we ought to look at couple of ways to create lists from text the first is to simply convert string into list with the list(function (as with all python typesthere is function of the same name as the type that converts into the type applying list(to string gives list of the characters in the string |
10,103 | built in method 'helloworld!split(splits on spaces ['hello,''world!'str list str str the string type has methods of its own one of these is split(which returns list of the components of the string as separated by white space the split(method can take an argument identifying other characters to split on if you want to get into more complex splitting of text we recommend you investigate regular expressions or format-specific techniques ( for comma-separated values |
10,104 | "methodsobject method(argumentsappend(itemreverse(sort(insert(index,itemremove(itemhelp help(objecthelp(object methodsorting list sort(sorted(listconcatenation +[ , , [ , , primes +[ |
10,105 | minutes |
10,106 | odds [ does not include odds remove( try to remove traceback (most recent call last)hard error file ""line in valueerrorlist remove( ) not in list must be in the list before it can be removed recall that list' remove(method will give an error if the value to be removed is not in the list to start with we need to be able to test for whether an item is in list or not |
10,107 | odds [ in odds false in odds true not in odds true python uses the keyword "infor this purpose it can be used on its own or as part of "not in"value in listevaluates to booleantrue or false |
10,108 | first ** - + % / * == != >= > <= < not in in not or and last - + the list now contains every operator we meet in this course these operators fit naturally into the order of precedence while python does contain other operators that belong in this listwe will not be meeting them in this introductory course |
10,109 | if number in numbers numbers remove(numberwhat' the differencewhile number in numbers numbers remove(number we now have safe way to remove values from liststesting before we remove them quick questionwhat' the difference between the two code snippets in the slide |
10,110 | printing each element on line ['the''cat''sat''on''the''mat 'the cat sat on the mat there is an obvious thing to want to do with listand that is to work through each item in listin orderand perform some operation or set of operations on each item in the most trivial casewe might want to print each item the slide shows list of stringsprobably from the split(of string how do we print each item one after the other |
10,111 | adding the elements of list [ - what is the sum of an empty list[ alternativelywe might want to accumulate the items in list in some way for examplewe might want to sum the numbers in list this is another example of applying an operation to each item in list this time the operation is folding the list itemsvalues into some final result in this case we would probably need an initial value of the result that it takes before any items get folded into it what is the sum of an empty listzerois that an integer zeroa floating point zeroor complex zero |
10,112 | squaring every number in list [ - [ finallywe might want to convert one list into another where each item in the output list is the result of some operation on the corresponding item in the input list |
10,113 | name of list list words ['the''cat''sat''on''the''mat 'for word in words new python looping construct print(wordprintwhat we want to do with the list items python has construct precisely for stepping through the elements of list this is the third and final construct we will meet in this course we have already seen if and while in this course now we meet for this looping constructbut rather than repeat while test evaluates to trueit loops once for each item in list furthermore it defines name which it attaches to one item after another in the list as it repeats the loop |
10,114 | words ['the''cat''sat''on''the''mat 'keywords for word in words print(wordcolon followed by an indented block we'll look at the expression one step at time the expression is introduced by the "forkeyword this is followed by the name of variable we will return to this in the next slide after the name comes the keyword "inwe have met this word in the context of lists before when we tested for an item' presence in list this is different use we aren' asking if specific value is in list but rather we are asserting that we are going to be processing those values that are in it after this comes the list itselfor more often the name of list all it has to be is an expression that evaluates to list the line ends with colon the lines following the colon are indented marking the block of code that is to be run once for each item in the list |
10,115 | words ['the''cat''sat''on''the''mat 'defining the loop variable for word in words print(wordusing the loop variable now let' return to the name between "forand "inthis is called the "loop variableeach time the loop block is run this name is attached to on item of the list each tim the loop is run the name is attached to the next item in the list the looping stops after the name has been attached to the last item in the list |
10,116 | for word in words print(wordword list str str str str str str words first loop the first time the loop is run the "loop variablename is attached to the first element in the list |
10,117 | for word in words print(wordword list str str str str str str words second loop the loop gets run againbut this time the loop variable name is attached to the next element of the list |
10,118 | for word in words print(wordword list str str str str str str words third loop and the next |
10,119 | for word in words print(wordword list str str str str str str words fourth loop and the next |
10,120 | for word in words print(wordword list str str str str str str words fifth loop and the next |
10,121 | for word in words print(wordword list str str str str str str words final loop until finally it is linked to the final element of the list the loop is not run again |
10,122 | words ['the''cat''sat''on''the''mat 'for word in words print(wordfor py there is simple example of this in the file for py in your home directories python for py the cat sat on the mat |
10,123 | numbers [ - total set up before the loop for number in numbers total +number processing in the loop for py print(totalresults after the loop our second case was an "accumulatoradding the elements in list here we establish an initial start value for our total of and give it the name "sumthen we loop through the elements in the listadding their values to the running total as we move through them the unindented line after the loop block marks the end of the loop block and is only run after all the looping is completed this prints out the value of the total now that all the numbers in the list have been added into it python for py |
10,124 | numbers [ - squares set up before the loop for number in numbers squares append(number** processing in the loop for py print(squaresresults after the loop our third example made new list from the elements of an old list for examplewe might want to take list of numbers and produce the list of their squares in this case the usual process is that rather than have an accumulator with an initial value we start with an empty list andas we loop through the input valueswe append(the corresponding output values python for py [ |
10,125 | numbers [ - squares for number in numbers loop variable only meant for use in loopsquares append(number** print(numberbut it persists there is one nicety we should observe the loop variable was created for the purpose of running through the elements in the list but it is just python nameno different from the ones we establish by direct assignment while the for loop creates the name it does not clean it up afterwards |
10,126 | numbers [ - squares for number in numbers squares append(number** del number delete it after use it is good practice to delete the name after we have finished using it so we will follow our for loops with del statement this is not required by the python language but we recommend it as good practice |
10,127 | testing items in lists in [ , , , for loops total for number in [ , , , ]total +number del number loop variables for number in [ , , , ]total +number del number true |
10,128 | what does this printnumbers [ total total_so_far [for number in numberstotal +number total_so_far append(totalprint(total_so_far minutes |
10,129 | python "magic"treat it like list and it will behave like useful list what can "itbe we have seen already that every python type comes with function that attempts to convert other python objects into that type so the list type has list(function howeverwith lists python goes further and puts lot of work into making this transparent and convenient in very many cases in python you can drop an object into list construct and it will act as if it was listand convenient list at that |
10,130 | recalllist('hello'for letter in 'helloprint(lettergets turned into list [' '' '' '' '' ' for py for examplewe know that if we apply the list(function to string we get the list of characters but the python "treat it like listmagic means that if we simply drop string into the list slot in for loop then it is treated as exactly that list of characters automatically python for py |
10,131 | built in to pythonrange(start,limitfor number in range( , )print(number not included there are other python objects whichwhile not lists exactlycan be treated like lists in for loop very important case is "rangeobject note that the range defined by and starts at but ends one short this is part of the whole "count from zerobusiness |
10,132 | not actually listsrange( , range( , but close enoughlist(range( , )[ treat it like list and it will behave like list strictly speaking range is not list but it is close enough to list that when you drop it into for loopwhich is its most common use by farthen it behaves like the list of numbers |
10,133 | most common usefor number in range( )inefficient to make huge list just for this "iteratoranything that can be treated like list list(iteratorexplicit list so why does the range(function not just produce listwellits most common use is in for loop only one value is required at time if the list was explicitly created would waste computer memory for all the items not in use at the time and computer time for creating them all at once (truth be toldfor the purposes of this course you wouldn' notice |
10,134 | via list(range( [ start at range( [ range( [ every nth number range( - [ negative steps the range(function can be used with different numbers of arguments single argument gives list running from zero to the number two arguments gives the lists we have already seen third argument acts as "strideand can be negative |
10,135 | primes len(primes list(range( )valid indices [ [ now that we have the range object we can move on to one of the most important uses of it so far we have used for loop to step through the values in list from time to time it is important to be able to step through the valid indices of the list observe that if we apply the range(function to single number which is the length of list then we get list of the valid indices for that list |
10,136 | primes [ for prime in primesprint(primesimpler for index in range(len(primes))print(primes[index]equivalent what good is list of valid indicesthere are two ways to step through the values in list one is directlythis is the method we have met already the second is to step through the indices and to look up the corresponding value in the list these are equivalent and the first method we have already seen is shorter to write so why bother with the second |
10,137 | list list consider operations on two lists concrete example might be the "dot productof two lists this is the sum of the products of matching elements so [ [ how might we implement this in python |
10,138 | list [ list [ indices sum for index in range(len(list )sum +list [index]*list [indexprint(sumdealing with values from both lists at the same time we can approach this problem by running through the valid indices and looking up the corresponding values from each list in the body of the for loop |
10,139 | greek ['alpha''beta''gamma''delta'greek_i iter(greekiter next(greek_i'alphaoffset next(greek_i'betastr str str str we will look little more closely at iterators so that we can recognise them when we meet them later if we start with list then we can turn it into an iterator with the iter(function an iterator created from list is essentially the same as the list with note of how far through the list we have read this reference starts at zeroobviously python provides next(function which can act on any iterator which returns the next value (or the first if we've not startedand increments this internal counter |
10,140 | next(greek_i'gammanext(greek_iiter str str str str 'deltanext(greek_itraceback (most recent call last)file ""line in stopiteration note that next(complains vigorously if we try to run off the end for this coursewhere these errors are all fatal it means that we can' use next(directly we don' need towe have the for loop which handles the error for us |
10,141 | non-lists as lists for letter in 'hello'range(range(limitrange(start,limitrange(start,limit,steprange( , [ , , , "iteratorsgreek_i iter(greeknext(greek_iindices of lists for index in range(len(things))parallel lists |
10,142 | complete exercise py list list difference - - square add minutes this exercise develops the python to calculate the square of the distance between two points we could use our square root python from earlier to calculate the distance itself but we will meet the "realsquare root function later in this course so we'll hold back from that for now |
10,143 | primes [ primes [ the list primes[ an item primes[ : [ part of the list there is one last piece of list pythonry we need to see python has syntax for making copies of parts of listswhich it calls "slicesifinstead of simple index we put two indices separated by colon then we get the sub-list running from the first index up to but excluding the second index |
10,144 | from to up to but not including primes[ : primes [ primes[ : [ item not included the last index is omitted as part of the "count from zerothing |
10,145 | primes [ primes[ : [ primes[: [ primes[ :[ primes[:[ we can omit either or both of the numbers missing the first number means "from the startand missing the second means "right up to the end |
10,146 | primes [ primes[ : [ primes[ : : [ primes[ : : [ we can also add second colon which is followed by stridejust as with range( |
10,147 | letters [' ',' ',' 'alphabet letters list letters str str str alphabet slices allow us to make copies of entire lists if we use simple name attachment then we just get two names for the same list |
10,148 | letters[ 'aprint(alphabet[' '' '' 'list letters str str str alphabet changing an item in the list via one name shows up via the other name |
10,149 | letters [' ',' ',' 'slices are copies alphabet letters[:letters alphabet list str list str str slices are copiesthoughso if we attach name to slice from list -even if that slice is the entire list -then we have two separate lists each with their own name attached |
10,150 | letters[ 'aslices are copies print(alphabetalphabet [' '' '' 'letters list str str list str str so changes in one don' show in the other because they are not the same list |
10,151 | slices end-limit excluded slices are copies items[from:toitems[from:to:strideitems[:toitems[:to:strideitems[from:items[from::strideitems[:items[::stride |
10,152 | predict what this python will do then run it were you rightexercise py foo [ bar foo[ : : bar[ +foo[ foo[ bar[ print(bar minutes |
10,153 | text" string of characterslist list( str str str str str str recall that text is called "stringobject because it is "string of characterswe have already seen that there is straightforward wayusing the list(functionto turn string into the literal list of characters |
10,154 | 'helloworld!'[ simple indexing ' 'helloworld!'[: slicing 'hell we can go further it is actually possible to refer to single characters out of strings by giving the position of that character as an index we can create substrings of the text by using slicing note that this gives second stringnot list |
10,155 | 'helloworld!'[ 'ctraceback (most recent call last)file ""line in typeerror'strobject does not support item assignment howeverwe cannot use the index notation on the left hand side of an assignment we cannot use this to change the contents of string string objects in python are immutablejust like integers if you want different string you have to create it from scratch |
10,156 | input output reading writing txt dat csv now we will look at something completely different that will turn out to be just like listfiles we want our python scripts to be able to read in and write out files of text or data we will consider reading files first and writing them second |
10,157 | file name 'treasure txtstring book file 'treasure islandstring "openingthe file file object reading from the file file contents "closingthe file finished with the file reading from file involves four operations bracketing three phases we start with file name this is string of characters want to be pedantic about something in this coursea file name is not file file is lump of data in the computer' long-term store file name is short piece of text we link file name to file by process called "opening the filethis takes the file name and creates python file object which will act as our conduit to the file proper we will use this file object to read data from the file into the python script when we are done reading data out of the file (via the file objectwe will signal to both python and the operating system that we are done with it by "closingit this disconnects us from the file and we would have to re-open it if we wanted more data |
10,158 | python function file name read-only [textbook open('treasure txt'' '"modepython file object read-only is the default book open('treasure txt we will start with opening file we start with just the file name this is passed into the open(function with second argument' 'indicating that we only want to read the file the function hooks into the operating systemwhich looks up the file by namechecks that we have permission to read itrecords the fact that we are reading itand hands us back handle -the file object -by which we can access its contents |
10,159 | "next linepleasefile object line next(bookfirst line of file line includes the "end of line'treasure island\ now that we have this hook into the file itselfhow do we read the data from itfile objects are iteratorsso we can apply the next(function to them to get the next linestarting with the first |
10,160 | line next(booksecond line of file line '\na blank line line next(bookline third line of file 'part one\ note that "blankline actually contains the end of line character it has length and is not an empty stringlength |
10,161 | method built in to file object book close(frees the file for other programs to write to it when we are done reading the data we need to signal that we are done with it python file objects have close(method built into them which does precisely this |
10,162 | book text input/output <_io textiowrapper name='treasure txtencoding='utf- 'file name character encodinghow to represent letters as numbers utf- means "ucs transformation format - -bitucs means ""universal character set this is defined by international standard iso/iec information technology -universal multiple-octet coded character set (ucsfor more information than you could possibly want on this topic visit the unicode web pageswww unicode org |
10,163 | file name text encoding file treasure txt "offset"how far into the file we have read utf- treasure islandpart onethe old buccaneerpointer to the file on the file system the python file object contains lot of different bits of information there are also lots of different sorts of file objectbut we are glossing over that in this introductory course what they share is reference into the operating system' file system that identifies the specific file and acts as the declaration to the operating system that the python process is using the file they also share an "offsetthis is number that identifies how far into the file the program has read so far the next(function reads from the offset to the next new line and increases the offset to be the distance into the file of the new line character the file object also records the name it was opened from and the text encoding it is using to convert bytes in the file to characters in the program |
10,164 | treat it like list and it will behave like list list(file_objectlist of lines in the file book open('treasure txt'' 'lines list(bookprint(lines given that file is an iteratorwe can simply convert it into list and we get the list of lines |
10,165 | book open('treasure txt'' 'lines_a list(bookprint(lines_ahuge output lines_b list(bookprint(lines_b[empty list notehoweverthat the act of reading the file to get the lines reads through the fileso doing it twice gives an empty result second time round |
10,166 | book open('treasure txt'' 'file object starts with offset at start lines_a list(bookprint(lines_aoperation reads entire file from offset offset changed to end of file lines_b list(bookprint(lines_b[operation reads entire file from offset so there' nothing left to read recall that the reading starts at the offset and reads forwards -to the end of the file in this example it also moves the offset to what was last read so the offset is changed to refer to the end of the file |
10,167 | book open('treasure txt'' 'lines_a list(bookprint(lines_abook seek( set the offset explicitly lines_b list(bookprint(lines_b we can deliberately change the offset for text files with lines of different lengths this can be more complex that you would imagine the only safe value to change the offset to is zero which takes us back to the start of the file |
10,168 | book open('treasure txt'' 'for line in book treat it like list being able to read single line of file is all very well converting an entire book into list of its lines might prove to be unwieldy what is the typical way to do itgiven that files can be treated like lists the easiest way to process each line of file is with for loop |
10,169 | book open('treasure txt'' 'n_lines line count for line in book read each line of the file n_lines + print(n_linesbook close(increment the count print out the count for examplewe could just increment counter for each line to count the number of lines |
10,170 | book open('treasure txt'' 'n_chars for line in book number of characters on the line n_chars +len(lineincrease the count by that many print(n_charsbook close( we could measure the length of the line and increment the counter by the number of characters in the line to count the total number of characters in the file |
10,171 | opening file to read book open(filename' 'reading file for line in bookclosing file book close(file offset book seek( |
10,172 | complete script to count lineswords and characters of file exercise py minutes hintrecall the split(method that strings have'helloworld!split(['hello,''world!'once this script is complete you will have written an equivalent of the standard (albeit simpleunix command line tool "wc"python exercise py file nametreasure txt treasure txt wc treasure txt treasure txt |
10,173 | file name 'treasure txtstring 'treasure islandstring book file "openingthe file data to write writing to the file file object "closingthe file finished with the file enough of reading files robert louis stephenson has prepared for us let' write our own this is again three phase process we will open file for writingwrite to it and then close it |
10,174 | open for writing [textoutput open('output txt' 'this will truncate an existing file opening file for writing is the same as opening it for reading except that the mode is 'wfor writing if the file already exists then this overwrites it the file gets truncated to zero bytes long because you haven' written to it yet |
10,175 | open for appending [textoutput open('output txt' ' if you do not want to overwrite the content of the fileyou can also open file for appending with mode 'ain all other regards appending will be the same as writing |
10,176 | file object method built in to file object output write(line data being written number of characters actually written len(line writeable file object has method write(which takes text string (typically but not necessarily lineand writes it to the file this has return valuewhich is the number of characters it managed to write note that if there are "issues(running out of spacemalfunctionsnetwork interruptionsthe system may not be able to write all the characters typically it doesthoughand the return code should match the length of the line |
10,177 | output write('alpha\ ' output write('be' typical usewhole line includes "end of linedoesn' have to be whole lines output write('ta\ ' output write('gamma\ndelta\ ' can be multiple lines how the data is chopped up between writes is up to you |
10,178 | output close(vital for written files it also has close(method |
10,179 | importance of closing data "flushedto disc on closure write python script "flushfile object file system closing files is even more important for written files that read ones it is only when file is closed that the data you have written to the python file object is definitely sent to the operating system' file this is process called "flushing the file to discwriting to disc is slow by computing standards sofor efficiency reasonssystems like python tend to wait until they have at least certain amount of data for file before they flush it to disc if your program exists before flushing then the data may be lost closing file signals that there will be no more data coming for it so python flushes whatever it has in hand to the disc as part of the closure process |
10,180 | files locked for other access open [' '(more problem for windows than unixopen [' ' there' more to it than just flushingthough holding file open signals to the underlying computer operating system that you have an interest in the file how the operating system reacts to this varies from system to systembut microsoft windows(tmwill lock file so that if you have it open for writing nobody else can open it for readingeven if you don' plan to write any more to it than you have already |
10,181 | output write('boo!\ 'writing text (str output write( writing non-text (inttraceback (most recent call last)file ""line in typeerrormust be strnot int write(only accepts text there is one last issue to address with writing data to files iunlike the print(functionthe write(function can only handle text arguments the print(function automatically converts non-text valueswrite(does not thereforewe must do the conversion ourselves |
10,182 | output write(str( )convert to textstr( output write('\ 'explicit end-of-line text formatting (later in the courseprovides more elegant solution we do this simply by calling the str(function which converts (almostanything directly into text we also need to explicitly add on the new line character to indicate the end of the line with the data on it later in this course we will see system python has for generating formatted text this will provide more elegant solution butuntil thenwe will make do with str(and \ |
10,183 | opening files for writing book open(filename' 'writing text book write(textwriting data book write(str(data)explicit ends of lines book write('\ 'closing the file is important book close( |
10,184 | the script exercise py prints series of numbers ending in change the script to write to file called output txt instead of printing to the console minutes |
10,185 | ( |
10,186 | input(promptbool(thinglen(thingfloat(thingopen(filenamemodeint(thingprint(lineiter(listtype(thinglist(thingord(charrange(fromtostridechr(numberstr(thingnot that many"the python way" if it is appropriate to an objectmake it method of that object this is the complete set of python functions that we have met to date actually it' surprising how few there arenot how many python' philosophy leads to functions that only make sense for particular sort of object being methods of that objectnot free-standing functions we are now going to write our own functions |
10,187 | easier to read write test fix improve add to "structured programmingdevelop whymoving our scriptsfunctionality into functions and then calling those functions is going to make everything better this is the first step towards "structured programmingwhich is where programming goes when your scripts get too long to write in one go without really thinking about it |
10,188 | ( ( identify the inputs identify the processing identify the outputs so what do we need to dowell any functions starts by defining what inputs it needswhat it does with those inputs to generate the results and exactly what results/outputs it generates |
10,189 | sum list [ [ - [ "edge case to give ourselves simple but concrete example to keep in mind we will set ourselves the challenge of writing function that sums the elements of list this may sound trivial but immediately raises some interesting cases that need to be considered what is the sum of an empty listzerois that an integer zero or floating point zero(or complex zero?we will say it should sum to an integer zero |
10,190 | define function called name of function inputs def total)colon we will plunge straight into the python the python keyword to define function is "defthis is followed by the name of the function"totalin this case this is followed by pair of round brackets which will contain all the input values for the function finally there is colon to mark the end of the line and the beginning of the body of the function |
10,191 | name for the input def total(numbers)this name is internal to the function our function takes single inputthe list of numbers to be summed what goes inside the brackets on the def line is the name that this list will have inside the function' definition this is the "xin maths this internal names is typically unrelated to the name the list has in the main body of the script it is always good idea to name your inputs (and other variablesmeaningfully please try to avoid calling them " "" "or "zwe will call ours "numbers |
10,192 | def total(numbers)colon followed by indentation as ever with python colon at the end of line is followed by an indented block of code this will be the body of the function where we write the python that defines what the function actually does with the input(sit is given |
10,193 | def total(numbers)sum_so_far for number in numberssum_so_far +number "bodyof function for our function this is particularly simple |
10,194 | def total(numbers)sum_so_far these variables exist only within the function' body for number in numberssum_so_far +number the numbers name we specified on the def line is visible to python only within the function definition similarly any names that get created within the function body exist only within that function body and will not be visible outside nor will they clash with any other uses of those names outside the function body in our example code the name "numbersis defined in the def linethe "sum_so_farname is defined explicitly in the function body and the "numbername is defined by the for loop as its loop variable none of these interact with the python outside the function definition |
10,195 | def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far this value is returned return this value finally we need to specify exactly what value the function is going to return we do this with another python keyword"returnthe value that follows the return keyword is the value returned by the function when python reaches the return statement in function definition it hands back the value and ends the execution of the function body itself |
10,196 | and that' itdef total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far unindented after this and that' all that is involved in the creation of python function |
10,197 | and that' itall internal names internal no need to avoid reusing names all internal names cleaned up no need for del note that because of this isolation of names we don' have to worry about not using names that are used elsewhere in the script alsoas part of this isolation all these function-internal names are automatically cleared when the function finishes we do not need to worry about deleting them |
10,198 | def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far print(total([ ])the list we want to add up we use this function we have defined in exactly the same way as we would use function provided by python |
10,199 | def total(numbers)sum_so_far for number in numberssum_so_far +number return sum_so_far print(total([ ])the function we have just written |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.