id
int64
0
25.6k
text
stringlengths
0
4.59k
10,000
( ** mid-point and again
10,001
** so change lower bound to give an interval of length /
10,002
one more iteration find the mid-point square it compare the square to do you change the lower or upper bound minutes please make sure that you understand the principle and do one more iteration by hand
10,003
apologies for spending so long on the maths but this is general situation you must understand the situation before you can program it
10,004
lower upper middle (lower+upper)/ so now let' start the implementation of this process in python we will do exactly the same mathsbut this time with python syntax first we set the end points for the interval of uncertainty and attach names to the two -values the names lower and upper are attached to the end pointslower upper we establish the -value of the mid-point and attach the name middle to itmiddle (lower+upper)/ this is exactly where we started last timebut we have attached python names to the values
10,005
middle** true lower middle print(lowerupper nextwe find the -value corresponding to the mid-point (by squaring the -value and ask if it is less than the number whose square root we are looking for middle** recall that this will return python boolean valuetrue or false the squared value is which is less than ( we get trueso we raise the lower limit of the interval to the mid-point lower middle in this example we print the -value at each end of the interval to track our progress
10,006
middle (lower+upper)/ print(middlemiddle** so we do it again we re-calculate the -value for the mid-point note that because we changed the value the name lower was attached to the python instruction is identical to the one we gave first time roundmiddle (lower+upper)/ we do some additional printing to track progress
10,007
middle** false upper middle print(lowerupper againwe ask if the mid-point' -value ( its -value squaredis above or below our target of middle** and this time get boolean false because the value is greater than (our test evaluates to falsewe change the value of the upper bound of the interval by attaching the name upper to the -value of the mid-pointupper middle the values being handled are exactly the same as they were when we did it as "raw mathsbut this time they have names
10,008
middle (lower+upper)/ print(middlemiddle** we now do third iteration
10,009
middle** true lower middle print(lowerupper this time the test evaluates to true so we change lower
10,010
middle (lower+upper)/ print(middlemiddle** fourth iteration
10,011
middle** true lower middle print(lowerupper and another true so we change lower again and that' enough of stepping through it manually
10,012
lower upper middle (lower+upper)/ print(middlemiddle** middle** lower middle upper middle print(lowerupper let' look at the python code we have used we started by initializing our interval of uncertaintylower upper then we started the operations we would repeat by calculating the -value of the mid-pointmiddle (lower+upper)/ we squared this and compared the squared -value with our target valuemiddle** andbased on whether this evaluated to true or false we ran eitherlower middle orupper middle then we ran the iteration again
10,013
lower upper set up loop middle (lower+upper)/ print(middlemiddle** choice middle** lower middle upper middle print(lowerupper structurallywe need to be able to do two things beyond our current knowledge of python we need to be able to run certain instructions time and time again ("looping"and we need to be able to choose one of two different actions depending on whether boolean value is true or false
10,014
before loop test loop body should the loop run (again)what is run each loopafter we will address looping first loop has number of components strictly not part of the loop are the "beforeand "aftersections but these give context and may use values needed by the loop the loop itself must have some sort of test to indicate whether the loop should run again or whether the looping can stop and control can pass to the "aftercode then there must be the set of instructions that will be run each time the loop repeats we call this the "bodyof the loop
10,015
before number loop test number < loop body after print(numbernumber + print('done!' let' consider an example that' simpler than our square root loopcounting from to our "beforeblock initializes the attachment of name number to value number our test sees if number is attached to value less than or equal to (our final value)number < recall that this evaluates to boolean value if the test evaluates to true then we run the loop body this has two linesthe first to print the value of number and the second to increase it by oneprint(numbernumber + if the test evaluates to false then we don' loop and exit the structure we have pointless print statement as place-holder for more substantive code in serious scriptsprint('done!'this is what we want to encode in python
10,016
number number while number < number < print(numbernumber + print('done!'print(numbernumber + print('done!' this is how we encode the structure in python we will examine it element by elementbut at first glance we observe "whilekeyword and colon on either wise of the test and the loop body being indented four spaces
10,017
number "whilekeyword loop test while number < colon print(numbernumber + print('done!' we will start by looking at what we have done to the test the test itself is number < which is python expression that evaluates to booleantrue or false we precede the test expression with the python keyword "whilethis is what tells python that there' loop coming it must be directly followed by an expression that evaluates to boolean we follow the test expression with colon this is the marker that the expression is over and must be the last element on the line note that the test evaluates to true for the loop to be run and false for the loop to quit we are testing for "shall the loop keep goingnot "shall the loop stoppython tests for whilenot until
10,018
number while number < print(numbernumber + loop body indentation print('done!' the loop bodythe code that is repeatedappears on the lines following the "while lineboth its lines are indented by four spaces each note that the "aftersection is not indented
10,019
number while number < print(numbernumber + print('done!'while py python while py done first let' check that this really works in the file while py in your home directories you will find exactly the code shown in the slide run it and watch python count from to
10,020
number while number < four spacesindentation indicate "blockof code print(numbernumber + print('done!'the block forms the repeated lines the first unindented line marks the end of the block the four spaces of indentation are not cosmetic sequence of lines that have the same indentation form blocks in python and can be thought of as single unit of code in this case both lines get run (againor neither of them do the indented block is ended by the first line that follows it with no indentation
10,021
( ( ( )( ( )(ii ( )(iii ( if this seems little alien consider the "legaleseof complex documents they have paragraphssub-paragraphs and sub-sub-paragraphs etc each indented relative to the one containing them
10,022
shell while do done while do done syntax clarity syntax clarity marking blocks of code is one of the places where computing languages differ from one another some have special words that appear at the start and end of blocks like "doand "doneothers use various forms of brackets like "{and "}interestinglyprogrammers in these languages typically also indent code within the blocks for visual clarity python simply uses the indentation for its core syntax rather than just for ease of reading purely for interestthe shell and versions of while py are also in your home directory as while sh and while
10,023
while test to keep looping code blocks before while test action action action afterwards indentation
10,024
for each scriptwhile py predict what it will do while py run the script while py were you rightwhile py while py to kill running scriptctrl minutes
10,025
uncertainty tolerance - / / what we want / / what we get now let' return to our square root example we have loop the body of which halves the length of the interval of uncertainty we need to put this into python loop so we need corresponding loop test one typical approach is to test to see if the interval is longer than some acceptable value in this case we will demand that the interval have length no longer than - (it will take halvings to get from an initial length of to something less than - common name for an "acceptable uncertaintyis "tolerance"the amount of uncertainty we are prepared to tolerate
10,026
uncertainty tolerance while uncertainty tolerance do stuff we need python test for this recall that python needs test that evaluates to true for the loop body to run our test then is "is the current uncertainty larger than the acceptable tolerance?we will set nametoleranceto have the value - calculate an uncertainty each loop and perform the test uncertainty tolerance if this is true then we need to keep going if it is false then we can stop
10,027
tolerance - lower upper uncertainty upper lower while uncertainty tolerance set up loop middle (lower upper)/ choice print(lowerupperuncertainty upper lower soif we return to our basic structure we can now see how python' while syntax fits in we establish tolerance we establish an initial uncertainty we test for uncertainty tolerance as the loop test we recalculate the uncertainty at the end of the loop block for use in the next round of the test all we have to do now is to add in the choice block
10,028
choice middle** lower middle upper middle middle** true or false true lower middle false upper middle once again we have test followed by some actions this timehoweverthe test doesn' decide whether or not to run block of code againbut rather which of two blocks of code to run once our test - python expression that evaluates to boolean -is simplymiddle** and if this evaluates to true then we change the lower boundlower middle and if it evaluates to false then we change the upper boundupper middle either wayonce one or the other has run we move on and do not return to the test
10,029
text input('number'number int(textif number = print('even number'elseprint('odd number'print('that was fun!'ifthenelse py python ifthenelse py number even number that was fun python ifthenelse py number odd number that was fun againwe will look at an example that demonstrates just the structure there is script in your home directories called ifthenelse py which illustrates the structure on its own mathematical notethe script tests for number being even by using the "remainderoperator "%to calculate the remainder if we divide by and testing for that remainder being
10,030
if keyword test if number = colon print('even number'else upper middle print('that was fun!' the first line of the test looks very similar to the while syntax we have already seen in this casehoweverit uses new keyword"ifthe if keyword is followed by the testa python expression that evaluates to boolean the line ends with colon
10,031
if number = print('even number'else run if test is true indentation upper middle print('that was fun!' the test line is immediately followed by the block of code that is run if the test evaluates as true because it is block of code it is indented by four spaces to mark it as block this example has single linebut the block can be as long as you want this block is sometimes called the "then-blockbecause "if the test is true then run this block
10,032
if number = print('even number'else elsekeyword upper middle run if test is false print('that was fun!'indentation after the then-block comes another new keyword"else:this is not indented and is level with the "ifto indicate that it is not part of the thenblock it is then followed by second block of codeknow as the "else-blockthis is the code that is run if the test evaluates as false againbecause it is block of code it is indented the else keyword and its corresponding block are optional you can do nothing if the test returns false the then-block is compulsory
10,033
if number = print('even number'else upper middle print('that was fun!'run afterwards regardless of test after the else-block the script continues the print line is unindented so is not part of the else-block this line is run regardless of the result of the test
10,034
middle (lower upper)/ before if middle** lower middle else if block upper middle print(lowerupperafter let' return to our square root example here we have the creation of mid-point -value followed by an if-test on itmiddle (lower+upper)/ if middle** this switches between two single-line code blocks if the test evaluates to true then the then-block is runlower middle and if it evaluates to false then the else-block is runelseupper middle after one or other is run the print statement is always runprint(lowerupperall we have to do now is to fit it inside our while loop
10,035
if before elseif test action action elseaction choice of two code blocks indentation afterwards
10,036
for each scriptifthenelse py predict what it will do ifthenelse py run the script ifthenelse py were you right minutes
10,037
tolerance - lower upper uncertainty upper lower while uncertainty tolerance middle (lower upper)/ if middle** if starts indented lower middle else doubly indented upper middle print(lowerupperuncertainty upper lower so how do we embed an if-test with its two code blocks inside while-loop as the loop' bodythe body of the while-loop is indented four spaces so we start the if-test indented four spaces and make its indented blocks doubly indented
10,038
tolerance - lower upper uncertainty upper lower while uncertainty tolerance middle (lower upper)/ spaces if middle** lower middle spaces else upper middle print(lowerupperuncertainty upper lower so if our standard indentation is four spaces then the doubly indented sections are indented eight spaces this is simple example with only two levels of indentation python can 'nestblocks much further than this
10,039
tolerance - lower upper uncertainty upper lower while uncertainty tolerance middle (lower upper)/ if middle** lower middle elseupper middle print(lowerupperuncertainty upper lower sqrt py python sqrt py the file sqrt py in your home directories contains the code as described in the slide it produces very nice approximation to the square root of
10,040
tolerance - lower upper uncertainty upper lower while uncertainty tolerance middle (lower upper)/ if middle** lower middle else upper middle print(lowerupperuncertainty upper lower so now we have the script for the square root of the next thing to do is to generalize it to produce square roots of any number
10,041
text input('number'number float(textif middle** number obviously we have to input the number whose square root we want we have already seen how to do this and to convert it from string into floating point numbertext input('number'number float(textonce we have the number the test middle** is straightforwardly extended to middle** number
10,042
lower upper if then else we have to set initial bounds for our interval of uncertainty this is where it is important that you think about the problem before coding if the number whose square root is sought is less than then the square root is bigger than the number and less than if it is larger than then its square root is less than the number and bigger than in python terms this means we can test for the number being less than and set the bounds accordingly
10,043
if number lower number upper else lower upper number it looks like this
10,044
text input('number?'number float(textuser input if number lower number upper elselower upper number initialization tolerance - uncertainty upper lower while uncertainty tolerancemiddle (lower+upper)/ if middle** numberlower middle elseupper middle processing uncertainty upper lower print(lowerupper output sqrt py this gives us enough of script to see the overarching structure of scriptwe start with getting the data we need from the outside world ("input"then we set up any initial state we need based on that ("initialization"then we do our processing finally we reveal our results ("output"typically the processing phase takes longest to runbut note thatas hereit is often not the majority of the lines of code
10,045
need to catch negative numbers if number print('number must be positive!'exit(quit immediately "elseis optional we can improve our code step missing from the previous script is "input validationwhere we check that the input makes sense we ought to check that we have not been asked to generate the square root of negative number
10,046
text input('number?'number float(textuser input if number print('number must be positive!'exit(input validation if number lower number upper elselower upper number initialization the input validation phase comes straight after the input itself
10,047
text input('number?'number float(textif number print('number must be positive!'exit(elif number lower number upper elselower upper number elif"else if sqrt py howeverit can be integrated with the initialization phaseand often is after allif you can' initialize from the input then the input isn' valid this leads us to multi-stage test of the number whose square root we wantis it less than if notis it less than if not then python has an extension to the simple if else test to allow for the "if not then is it situation "elifintroduces test and corresponding block of code the code is called only if the previous if test failed and its own test passes
10,048
text input('number?'number float(textif number print('number is negative 'elseif number print('number is between zero and one 'elseif number print('number is between one and two 'elseif number print('number is between two and three 'elseprint('number is three or more 'stacked clauses get unwieldy to take an extreme exampleconsider this multi-level test the continual nesting inside the else clauses causes the whole script to drift to the right
10,049
text input('number?'number float(textif number print('number is negative 'elif number print('number is between zero and one 'elif number print('number is between one and two 'elif number print('number is between two and three 'elseprint('number is three or more ' applying elif causes everything to slide back into place
10,050
nested structures while if chained tests if elif elif elsetesting inputs to scripts exit(
10,051
only attempt each part after you have the previous part workingexercise py edit the square root script to catch negative numbers edit the square root script to ask for the tolerance edit the square root script to catch negative tolerances minutes the minimum tolerance used in this example will work for target values up to limit in practice the minimum possible tolerance scales with the target square rootbut this is course on pythonnot numerical analysis
10,052
we have written our first real python script what did it dowhy did it do itneed to annotate the script sqrt py is real program now imagine you pass it to someone else or put it away for twelve months and come back to it forgetting how you wrote it in the first place chances are that the reader of your script might like some hints as to what it is doing and why "commentsin computer programs are pieces of text that describe what ios going on without getting in the way of the lines of code that are executed
10,053
the "hashcharacter "pound""number""sharplines starting with "#are ignored partial lines starting "#are ignored used for annotating scripts pythonin common with most other scripting languagesuses the hash character to introduce comments the hash character and everything beyond it on the line is ignored (strictly speaking the musical sharp character #is not the same as "#but people get very sloppy with similar characters these days this isn' at all relevant to python but the author is an annoying pedant on the correct use of characters and don' get him started on people who use hyphen when they should use an en-dash or em-dash
10,054
script to calculate square roots by bisection (cbob dowling licensed under gpl text input('number?'number float(textneed real number test number for validityset initial bounds if ok if number print('number must be non-negative!'exit(elif number lower number upper elselower upper number this is what commented script looks like
10,055
#!/usr/bin/python script to calculate square roots by bisection (cbob dowling licensed under gpl text input('number?'number float(textneed real number magic line for executable files fubar py instead of python fubar py you may encounter "hash plingfirst line in many imported python scripts this is part of some "unix magicthat lets us simplify our command lines we can' demonstrate it here because the mcs file server doesn' support unix semantics
10,056
comments "#character
10,057
comment your square root script from exercise minutes
10,058
whole numbers - floating point numbers complex numbers ( jtext 'the cat sat on the mat booleans true false we are about to introduce new python typeso we will take moment to remind ourseoves of the various python types we have met already
10,059
'hydrogen''helium''lithium''beryllium''boron''thorium''protactinium''uranium- - the new python type we are going to meet is called "list
10,060
hydrogenheliumlithiumberylliumprotactiniumuranium sequence of values the names of the elements values stored in order atomic number order individual value identified by position in the sequence "heliumis the name of the second element so what is lista list is simply sequence of values stored in specific order with each value identified by its position in that order so for an example consider the list of names of the elements up to uranium
10,061
sequence of values the prime numbers less than sixty values stored in order numerical order individual value identified by position in the sequence is the fourth prime or the list of primes up to note that list must be finite
10,062
primes literal list primes [ the whole list type(primesa python type so how might we do this in pythonwe will create list in python of the primes less than we can do this in single line as shown list in python is single python objectalbeit with multiple contentsand has its own typeunsurprisingly called "list
10,063
square brackets at the ends [ commas between items python presents (and acceptslists as series of values separated by commassurrounded by square brackets
10,064
primes [ literal list we are going to meet square brackets used fr lot of things so will build up summary slide of their various uses here is use
10,065
"index "value[ we still need to get at individual items in the list each is identified by its position in the list pythonin common with many programming languages (but not allstarts its count from zero the leading element in the list is "item number zerothe one that follows it is "item number oneand so on this numberthe position in the list counting from zerois called the "indexinto the list the plural of "indexis "indicesto keep yourself sanewe strongly recommend the language "item number instead of "the fourth item
10,066
primes [ index primes[ square brackets primes[ sohow do we get "item number from listwe can follow the list (ormore usuallya name attached to the listwith the index in square brackets
10,067
primes [ literal list primes[ index into list and this is the second use of square brackets
10,068
primes [ - - - - - - - - getting at the last item primes[- python has trick for getting at the last element of the list negative indices are also valid and count backwards from the end of the list typically the only case of this that is used in paractice is that the index - gets the last element of the list
10,069
list int primes[ int primes[ primes int primes[ int primes[ we've seen these box diagrams for simple python types already the structures for lists are little more complicated but only little the list type records how long it is and an ordered set of references to the actual objects it contains
10,070
list len(primes len(functionlength of list primes maximum index is note that the length of list is the number of items it contains the largest legitimate index is one less than that because indices count from zero
10,071
data ['alpha''beta''gamma'the list data[ initial value 'gammadata[ 'gchange value data[ check change 'gdata changed list ['alpha''beta'' ' so far we have created lists all in one go by quoting literal list we can use the indexing notation (square bracketsto change items in list too
10,072
right to left data ['alpha''beta''gamma'list str str str we can track what happens in that example in some detail we will start with the first linedefining the initial list as everpython assignment is done right to left the right hand side is evaluated as list of three itemsall of themstrings
10,073
right to left data ['alpha''beta''gamma'list str str str data this then has the name "dataattached to it
10,074
right to left data[ 'glist str str str str data new value now we come to the second line which changes one of these list items the right hand side is evaluated as string containing single characters that object gets created
10,075
right to left data[ 'glist str str str str data no longer referenced the assignment causes the reference within the string to be changed to refer to the new string and to stop referring to the previous one"gammain this case there are now no references to the "gammastring
10,076
right to left data[ 'glist str str str data python then clears out the memory used for that old string so that it can reuse it for something else this process is called "garbage collectionin computing
10,077
del data[ list str data[ str data[ str data[ data we can remove entries from the list too with the "delkeywordjust as we removed names the del keyword removes the reference from the list
10,078
del data[ list str data[ str no longer referenced str data[ data this leaves the string "betano longer referenced by anything
10,079
del data[ list str data[ str data[ data and garbage collection kicks in again
10,080
list int int primes int int primes[ we have remarked on couple of occasions that the largest valid index is number one less than the length of the list so what happens if you ask for an index greater than the largest legal value
10,081
len(primes primes[ primes[ traceback (most recent call last)file ""line in indexerrorlist index out of range type of error description of error you get an error unsurprisingly the type of the error is an "indexerror-something went wrong with an index the error message specifies that the index asked for was outside the valid range
10,082
primes[ traceback (most recent call last)file ""line in indexerrorlist assignment index out of range same type of error similar description of error but with "assignment note that we can' use indicies beyond the limit to extend list either
10,083
lists [ index primes[ count from zero primes[ deletion del primes[ length len(primesover-running primes[
10,084
track what the value of numbers is at each stage of this sequence of instructions numbers [ numbers[ del numbers[ numbers[ numbers[ numbers[ minutes do this by hand after each linework out what you think numbers will be and then print it to see if you were right to find outlaunch an interactive python and run each line followed by the line print(numbersalternativelythe script exercise py does it in script
10,085
list same list list new length int int int int int int extra item int sohow can we extend list
10,086
primes [ function built into list primes append( primes the list is now updated [ this is the python syntax for appending an item to the end of list you won' recognise the syntaxit is something new
10,087
the list connecting dot primes append( append(the value to append all lists have this function built in so we need to look at this new construction we have the list"primes"followed by dot which acts as connector this is followed by the name of function"appendthis function is not standard python function like print(or len(instead it is function that is "built into the list itself the list has its own function which appends to that list alternativelythink of "primes append()as function that appends to primes
10,088
behaves just like function object function function that has special access to the object' data (arguments these built in functions are called "methodsormore precisely"methods of the objectare used all over python and are general concept across an entire type of programming called "object oriented programming
10,089
print(primes[ primes append( primes append( the function doesn' return any value primes append( primes append( it modifies the list itself print(primes[ we can use the append(method repeatedly to extend the list as far as we want
10,090
numbers [ numbers reverse(the function doesn' return any value print(numbers[ it modifies the list itself append(is not the only method built into lists for example reverse(takes the list and reverses its contents note that it doesn' return reversed list as valuet doesn' return anything at all it silently reverses the content of the list itself also note that it takes no argumentthe brackets on the end of the function are empty
10,091
numbers [ numbers sort(the function does not return the sorted list print(numbers[ it sorts the list itself numerical order similarlythe sort(method doesn' return sorted list but silently sorts the list internally
10,092
greek ['alpha''beta''gamma''delta'greek sort(print(greek['alpha''beta''delta''gamma'alphabetical order of the words more or less any type can be sorted text sorting carries all the cautions about the complexities of collation that we covered under comparisons
10,093
greek ['alpha''gamma''delta'greek insert( 'betawhere to insert what to insert greek ['alpha''beta''gamma''delta' displaced the append(method sticks an item on the end of list if you want to insert an item elsewhere in the list we have the insert(method the insert(method takes two argumentsthe first is the item to be inserted the second is in index where it should go this does not replace the original item but rather "shuffles upall the items beyond it by one place to make room
10,094
numbers [ numbers remove( value to remove print(numbers[ del numbers[ index to remove there is remove(method this is passed value to remove from the list it then removes that value from the listwherever it is in the list contrast with with del where you had to know the index to remove
10,095
print(numbers[ there are two instances of numbers remove( print(numbers[ only the first instance is removed if the value appears more than once in list then only the first instance is removed trying to remove something that isn' there will lead to an error
10,096
help(numbershelp on list objectclass list(objectappendl append(object-append object to end paginationnext page back one page quit that' lot of methodsand it' only some of them how can we know all of themyou can always ask for help on any python object and you will be told all about the methods it possesses it is very formal documentation but the information is there incidentallypython uses program to paginate its help output press the space bar to move on one page"bto move back page and "qto quit
10,097
help(numbers appendhelp on built-in function appendappendl append(object-append object to end you can also get help on single method which is often simpler to deal with
10,098
greek ['alpha''beta''gamma''delta'greek sort(recallgreek sort(sorts the list "in placeprint(greek['alpha''beta''delta''gamma' we noted that the sort(method sorts the list itself experience shows that sorting is one of those operations where people want sorted copy of the list quite often
10,099
greek ['alpha''beta''gamma''delta'sorted(function returns sorted list ['alpha''beta''delta''gamma'print(sorted(greek)and leaves the list alone ['alpha''beta''gamma''delta'print(greek to assist with thispython offers standalone function called sorted(which makes copy of the list and sorts that copyleaving the original unchanged