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 oth...
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 lis...
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 ...
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 g...
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 abl...
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 ...
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 ...
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 a...
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 "...
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 t...
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...
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 ...
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 es...
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 ...
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 e...
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 ...
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 wou...
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 th...
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 correspon...
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 fro...
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 ...
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 hol...
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...
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 di...
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 someth...
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 fun...
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 c...
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...
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 re...
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 take...
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 wi...
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 tx...
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 writingwrit...
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 ...
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 p...
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 win...
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 prin...
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 ...
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 actua...
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 ...
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 ...
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 t...
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 ...
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 b...
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 th...
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 automati...
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