id
int64
0
25.6k
text
stringlengths
0
4.59k
9,900
'hello,\nworld!'hello\nworldpython uses \ to represent line breaks in strings '''helloworld!'''hello\nworldexactly the same it is also important to note that triple quotes are just trick for input the text object created is still standard python string it has no memory of how it was created also note that when python is representing the content of string object (as opposed to printing itit displays new lines as "\
9,901
four inputs'hello,\nworld!"hello,\nworld!'''helloworld!''"""helloworld!""same resultstr we have now seen four different ways to create string with an embedded new line they all produce the same string object
9,902
international text print(concatenation of strings special characters long strings
9,903
replace xxxx in exercise py so it prints the following text (with the line breaksand then run the script coffee cafe caffe kaffee \ altgr \ altgr minutes there is more than one way to do this you can get the line breaks with \ in single-quoted string or with literal line breaks in triple-quoted string an alternativebut not in keeping with the exerciseis to have four print(statements you can get the accented characters by using the \ sequences or you can type them in literally with the keyboard combinations shown (linux only
9,904
"variablesmessage 'helloworld!print(messagemessage='helloworld!hello py message 'helloworld!type(messagemessage str now we will move on to serious issue in learning any computing languagehow to handle names for values compare the two scripts hello py and hello py they both do exactly the same thing we can enter the text of hello py manually if we want using interactive pythonit will work equally well there the first line of hello py creates the string 'helloworld!but instead of printing it out directly the way that hello py doesit attaches name"message"to it the second line runs the print(functionbut instead of literal string as its argument it has this name instead now the name has no quotes around itand as said earlier this means that python tries to interpret it as something it should do something with what it does is to look up the name and substitute in the attached value whenever the name is usedpython will look it up and substitute in the attached value
9,905
message 'helloworld!print(messagetype(printprint function message str hello py both "printand "messageare the same this way both are names attached to python objects "printis attached to chunk of memory containing the definition of function and "messageis attached to chunk of memory containing the text
9,906
message input('yes?'print(messagepython input py input py input('yes?'yesboomessage booprint(message now that we know how to attach names to values we can start receiving input from the user of our script for this we will use the cunningly named "input()function this function takes some (typically shorttext as its argument it prints this text as prompt and then waits for the user to type something back (and press [|it then returns whatever the user typed (without the |]as its value we can use this function on the right hand side of an assignment recall that the assignment completely evaluates the right hand side first this means that it has to evaluate the input(functionso it prompts the user for input and evaluates to whatever it was that the user typed then the left hand side is processed and the name "messageis attached to this value we can then print this input text by using the attached name
9,907
number input(' ?'print(number python input py input py traceback (most recent call last)file "input py"line in print(number typeerrorcan' convert 'intobject to str implicitly string integer in the previous example script input py we simply took what we were given by input(and printed it the print(function is flexible beastit can cope with almost anything the script hello py attempts to take what is given and do arithmetic with itnamely add to it it failseven though we type number at input()' prompt this also gives us an error message and it' time to investigate python' error messages in more detail the first (the "trace back"tells us where the error was it was on line of the file input py it also tells us what was on the line recall that with syntax errors it also pointed out where in the line it realized something was going wrong the second part tells us what the error waswe tried to add string (textand an integer ( numbermore preciselypython couldn' convert the things we were adding together into things that we could add
9,908
number input(' ?'print(number python input py input py input(' ?'str int the problem is that the input(function always returns string and the string "character followed by character is not the same as the integer ten we will need to convert from the string to the integer explicitly
9,909
type('helloworld!'string of characters type( integer type( floating point number to date we have seen only two types"strand "builtin_function_or_methodhere are some more integers (whole numbersare type called "intfloating point numbers (how computers approximate real numbersare type called "floatthe input(function gave is "strwe want an "int
9,910
int(' ' int('- '- int(' - 'str str int int - valueerrorinvalid literal for int(with base ' - there is function -also called "int()-that converts the textual representation of an integer into genuine integer it copes with extraneous spaces and other junk around the integer but it does not parse general expressions it will take the textual form of numberbut that' it
9,911
float(' '' is string is floating point number float(' ' there is similar function called float(which creates floating point numbers
9,912
float( int( truncates fractional part int(- - the functions can take more than just stringsthough they can take other numbersfor example note that the int(function truncates floating point numbers
9,913
str( integer string float string ' str( ' there is also str(function for turning things into strings
9,914
int(anything integer float(anything float str(anything string functions named after the type they convert into in general there is function for each type that converts whatever it can into that type
9,915
python input py text input(' ?'number int(textprint(number so finally we can see what we have to do to make our failing script workwe need to add type conversion line
9,916
str text input(' ?'number int(textprint(number we can step through the script one element at time to see the totality of what we have written starting on the right hand side of the assignment operator (as we always do)initially we have the literal string which forms the body of the prompt
9,917
str input text input(' ?'number int(textprint(number nbtextnot number function str looking at the rest of the right hand side of the line we see that this is used by the input function its name is looked up and the string object "nis passed to it the function returns (evaluates toa second text object " note that this is string object (textand not an integer (number
9,918
text input(' ?'number int(textprint(number input function text str now that python has completd the evaluation of the right hand side its attention moves to the left hand side this identifies the nametextwhich is attached to this string value
9,919
text input(' ?'number int(textprint(number input function text str int function int moving to the right hand side of the second linethe name text is looked up to get the string " and the name int is looked up to give the function that converts strings into integers the string is passed to the function as its argument and the function returns an integer value this completes the evaluation of the right hand side
9,920
text input(' ?'number int(textprint(number input function text str int function number int moving now to the left hand sidepython sees the name number and attaches it to the integer value given by the right hand side
9,921
text input(' ?'number int(textprint(number number int scrolling upbecause slides are never big enough
9,922
text input(' ?'number int(textprint(number number int int function int the third line contains the expression number+ python looks up the name number to give an integer looks up the name to give functioncreates an integer directly and calls the function to add the numbers together this yields result of integer
9,923
text input(' ?'number int(textprint(number number int int print function finallypython looks up the name print to give function and passes it the freshly created value of integer as an argument
9,924
names types values name value strings integers floating point numbers reading in text input(prompttype conversions str(int(float(
9,925
replace the two xxxx in exercise py to do the following prompt the user with the text "how much? convert the user' answer to floating point number print plus that number minutes
9,926
- - now that we have some rudimentary understanding of python it' time to dive in little deeper to the three types we have met so far we are going to start with the whole numbers"integersin technical language mathematical notethe fancy is the mathematical symbol for the integers based on the german word zahlen
9,927
+ - spaces around the operator don' matter "no surprises we can start our handling of integers with some very basic arithmetic note that spaces around the plus and minus character are ignored adding or subtracting two integers simply gives third integer
9,928
there is no "xon the keyboard linuxaltgr shift use "*instead * still no surprises the arithmetical operations addition and subtraction have their usual mathematical symbols reflected on the standard keyboard we have plus sign and minus sign (actually "hyphen"character and we use them there is no multiplication symbol on the standard keyboard you can generate it as one of the octopus-friendly key combinationsbut it' not simple key insteadthe computing profession has settled on using the asterisk ("*"to represent multiplication on your keyboards this is [shift]+[ multiplying two integers gives third integer
9,929
there is no "/on the keyboard linuxaltgr shift use "/instead / this is floating point numbersurprise there is no division symbol on the keyboard without holding three keys down at the same time again convention has arisen to use the forward slash character (strictly called "solidus"for division so far there have been no surprises in python' integer arithmetic that changes with division not all integer division can be achieved precisely you cannot divide into exactly because of this python always returns type of number capable of representing fractional values ( floating point numbereven when the division would have been exact
9,930
fractions floats sometimes consistency floats always / / the designers of python decided that consistency of output was important and therefore because it might sometimes need to use float it should always use float note that even floating point numbers cannot exactly represent all fractions / can be precisely represented but / cannot we will return to the imprecision of floating point numbers when we look at them in detail (if you really want to stick to integers then python offers the "//operator which returns an integer answerrounded strictly down in case of fractional answers
9,931
there is no " on the keyboard use "**instead ** ** syntaxerrorinvalid syntax spaces around the operator don' matter spaces in the operator do just as there is no mathematical symbol on the keyboard for multiplication and divisionthere is no symbol at all for raising to powers mathematically we represent it by superscripting the power after the number being raised we can' do this on the keyboard so instead we cheat and invent our own symbol for the operation computing has split for this operation some languages use the circumflex accent ("^"and othersincluding pythonuse double asterisk"**note that while spaces around the operator are ignored you can' split the two asterisks
9,932
is number even or odduse "% % % - % remainder is always non-negative there' one last integer arithmetic operator we will use once in while another way to look at division is to ask what the remainder is after division python represents this concept by using the percent sign between to numbers to represent the remainder when the first number is divided by the second we will use it for one purpose only in this courseto determine if number is even or odd if number' remainder when divided by is then it' even and if the remainder is then it' odd
9,933
** ** ** ** ** now we will look at the numbers themselves we can ask the question "how big can an integer be?mathematicallyof coursethere is no limit in computer there are always limits each computer has only finite amount of memory to store information so there has to be limit we will see that python has no limits in principle and it is only the technical limit of the computer that can restrict us in practice this is never an issue for the size of integers we will experiment with large integers by repeated squaring we start with and keep squaring
9,934
** ** ** ** python takes it in its stride and happily carries on
9,935
except for machine memory there is no limit the python language has no limit on the size of integer
9,936
+fortran int integer* long integer* long long integer* out of the reach of or fortran this may sound rather trivial butin factpython is quite exceptional in this regard the compiled languages have to allocate space for their integers in advance and so place limits on how large they can grow
9,937
and that' it for whole numbers now we will look at floating point numbersa computer' way of storing fractional values this is computer' approximation to the real numbers as we will see it is problematic approximation the fancy is the mathematical symbol for the real numbersfrom the english word real
9,938
* equivalent to integer arithmetic for our basic operationsfloating point numbers behave just the same as integersusing the same operators to achieve the same results floating point division creates floating point number
9,939
if you are relying on this last decimal placeyou are doing it wrong significant figures so let' see our first problem floating point arithmetic is not exactand cannot be floating point numbers on modern hardware tends to give precision of significant figures you do see the occasional issue as shown on the slide butfranklyif you are relying on the exact value of the final decimal place you are doing it wroing
9,940
reallyif you are relying on this last decimal placeyou are doing it wrong not all imprecision is overt some of it can creep up on you computers work in base they can store numbers like / and / exactly but they cannot store numbers like / exactlyjust like we can' represent / exactly in decimal expansion the errors in storing / are small enoughthoughthat they are invisible at first howeverif they accumulate they become large enough to show through reallydon' depend on precise values
9,941
** so farso good ** + switch to "scientific notation + let' ask the same question about floats as we asked about integershow large can they bewe will repeat our approach of repeated squaring we fast-forward to start at squared and notice that we soon get anomolous responses when we square , , , we get number with the letter "ein it user' of pocket calculators at school may recognise this representationit indicates number between and multiplied by power of floating point numbers can only hold roughly significant figures of accuracy this means that when the integer needs more than digits something has to give
9,942
** + floating point ** integer the approximation isn' bad the error is in or approximately -
9,943
+ ** + + ** + + ** + so farso good + ** overflowerror( 'numerical result out of range'too big if we accept that our answers are now only approximate we can keep squaring the " -numberrepresentation of scientific notation is accepted on input by python when we come to square thoughwe hit another issuethis one fatal we get an "overflow errorthis means we have tried to create floating point number larger than python can cope with under some circumstances the "too bigproblem gives rise to sort-of-number called "inf(standing for "infinity"
9,944
significant figures - positive values - just for the recordfloating point numbers have limits both in terms of the largest and smallest numbers they can contain
9,945
( + )** ( + python also supports complex numbersusing for the square root of - we will not use them in this coursebut you ought to know they exist
9,946
arithmetic *integers no limitsfloating point numbers limited size limited precision complex numbers
9,947
replace the xxxx in exercise py to evaluate and print out the following calculations ( / ) ( / ) ( / ) minutes
9,948
we can do arithmetic on numbers what elsewe need to be able to compare numbers is less than yes it is is greater than no it isn'
9,949
asking the question asking the question true false now let' see that in python the "less thancharacter appears on the keyboard so we don' need anything special to express the concept like "**for powers python seems to answer the questions with "trueand "false
9,950
type(true"booleans int true bool int int the important thing to understand is that this is not just python reporting on test but rather the value generated by the test true and false are (the onlytwo values of special python type called "booleanused for recording whether something is true or not just as the "+operator takes two integers and returns an integer valuethe "<operator takes two integers and returns boolean booleans are named after george boolewhose work laid the ground for modern algebraic logic (his classic book' full title is "an investigation of the laws of thought on which are founded the mathematical theories of logic and probabilities"in true victorian style
9,951
bool true only two values bool false the boolean type has precisely two values
9,952
maths python =!<<>>double equals sign there are six comparison operations in python the equality comparison is defined in python with double equals sign"==the sign is doubled to distinguish comparison from assignment there is no "not equalssymbol on the standard keyboard insteadpython uses the "!=pair of characters (as with "**there must be no space between the two characters "less thanand "greater thanwe have already covered these are implemented directly by the "characters there are no "less than or equal toor "greater than or equal tokeysthoughso python resorts to double character sequences again
9,953
name value =value =value attach name to value compare two values if ever there was "classic typoin programming it is the confusion of "=and "==be careful
9,954
'cat'dogalphabetic ordering true 'cat'catuppercase before lowercase true 'dog'cattrue all uppercase before lowercase booleans typically arise from comparisons we can compare more than numbers (integers or floating pointwe can also compare strings text comparisons are based around the ordering of characters in the unicode character set note that all the uppercase letters in the latin alphabet precede all the lowercase letters so any text that starts with an uppercase letter counts as "less thanany text that starts with lowercase letter
9,955
python inequalities use unicode character numbers this is over-simplistic for "realuse "collationis whole field of computing in itself alphabetical ordergermanz< swedisho< please notehoweverthat this is just comparison of strings it is not general comparison of text ordering text is called "collationand is very compicated field for exampledifferent languages order characters differently if you want to learn more about this fieldstart with the unicode page on collation
9,956
number number and number number number true common requirement is to determine if number lies in particular range for this purposepython supports the mathematical notation the inequalities can be any combination that make sense
9,957
float(converts to floating point numbers int(converts to integers str(converts to strings bool(converts to booleans as with all python types there is function named after the type that tries to convert arbitrary inputs into booleans given that there are only two boolean values this tends to be very simple function
9,958
'false empty string 'fredtrue non-empty string false zero true non-zero true - true the empty string is mapped to false every other string is mapped to true for integers is mapped to false and every other value to true for floating point numbers is mapped to false and every other value to true
9,959
bool bool bool numbers have +-bool what do booleans havebool boolean types have their own arithmetic just like ordinary numbers it was the algebra of these that george boole developed
9,960
bool and bool bool true and true true true and false false false and true false false and false false both have to be true the first operation on booleans is the "andoperator the and of two booleans values is true if (and only ifboth its inputs are true if either is false then its output is false true and false false true and true true
9,961
and true true true true false false and true and false we are much more likely to encounter the input booleans as the results of comparisons that as literal values
9,962
bool or bool bool true or true true true or false true false or true true false or false false at least one has to be true the next boolean operation to look at is "orthe results of this operation is true if either of its inputs are true and false only if both its inputs are false
9,963
or true true true true true false or true or true againwe tend to encounter it more often with other tests than with literal booleans
9,964
not bool bool not true false not false true the final operation is "notthis takes only one input and "flipsit true becomes false and vice versa
9,965
not true not false false not true false not true
9,966
+ / ( (
9,967
+ / division first addition second
9,968
first ** - + % / * == != >= > <= < not and - + or last
9,969
comparisons =!numerical comparison alphabetical ordering 'dig'dugbooleans true boolean operators and or not conversions ' false false false other true false
9,970
predict whether these expressions will evaluate to true or false then try them 'sparrow'eagle 'dog'cator = = minutes
9,971
alpha alpha alpha alpha int int python creates an "integer in memory python attaches the name "alphato the value now let' go back to the attaching of names to values that we saw with our hello py script consider the simple python instruction shown python does two thingsstrictly in this orderfirstit notices the literal value (an integerso python allocates chunk of memory large enough and creates python object in it that contains python integer with value secondit creates the name "alphaand attaches it to the integer
9,972
alpha "rhs"right hand side evaluated first "lhs"left hand side processed second the key thing to note is that the processing happens right to left everything to the right hand side is processed first only after that processing is done is the left hand side considered in this example it' trivial it will become less trivial very soon so remember that the right hand side is evaluated before the left hand side is even looked at pscomputing uses the phrases "left hand sideand "right hand sideso often that they are typically written as "lhsand "rhs
9,973
beta int function rhs int int beta int lhs we can see slightly more involved example if we put some arithmetic on the rhs againthe rhs is evaluated first firstpython notices three "tokens"the the name "+and the it creates two integer objects just as it did with the previous example and it looks up pre-existing function object that does addition of integers secondpython triggers the addition function to generate third integer with the value this completes the evaluation of the rhs thirdpython creates name "betaand attaches it to the freshly created integer
9,974
gamma gamma now let' look at attaching name to value and then changing that value suppose we have these two lines of python in common with most--but not all--programming languagespython lets you set name for value and then change it
9,975
gamma rhs int the process begins exactly as it did for the alpha example above the right hand side of the first line sets up an integer in python memory
9,976
gamma gamma lhs int the left hand side of the assignment operation then attaches name to that valuejust as we saw before
9,977
gamma gamma rhs int gamma int now we move to the second line againpython processes the right hand side first this is an integer object and python creates that in memoryalongside the existing integer object that completes the processing of the second line' right hand side
9,978
gamma gamma lhs int gamma int so python then turns its attention to the second line' left hand side this requires python to attach the name gamma to the value just created given that the name already existspython detaches it from its old value and attaches it to the new oneleaving the old integer object behind
9,979
gamma gamma gamma garbage collection int int now there are no remaining references to the old integer python automatically cleans it upfreeing the space for re-use this is process called "garbage collectionin some languages you have to free up unused space yourselfin python the system does it for you automatically
9,980
gamma gamma gamma int this leaves python in its final state
9,981
gamma gamma gamma two separate integer objects int int python doesn' change an integer' valuepython replaces the integer python integers are "immutable there is one last observation to make about this process note that when we "changed gamma' valuewhat we did was to create whole new integer object and reset gamma to point to it we did not reach into the memory allocated to the integer object and change its value the fact that we cannot reach into python integers and change their values makes python integers "immutable
9,982
delta alpha alpha rhs alpha int function int int now we will consider more significantly involved exampleone with name on the rhs firstpython recognizes the three tokens on the rhs these are the name "alphathe "+and the literal integer secondit looks up the names the "alphais replaced by the integer and the name "+is replaced by the actual function that does addition the token is replaced by the actual integer in memory thirdit runs the function to give an integer object in memory
9,983
delta alpha lhs delta int only after all that is the lhs consideredand the name "deltais created and attached to the newly minted integer
9,984
delta int starting position print(delta now (finally!we get to the interesting case we start with the name delta being attached to the value
9,985
rhs delta delta delta delta int function int int then we run an assignment that has the name delta on both the left and right hand sides againfirst of all python focuses exclusively on the rhs the expression "delta is evaluated to give rise to an integer in python memory
9,986
lhs delta delta int delta int int delta rhs rhs int only once that evaluation is complete does python turn its attention to the lhs the name delta is going to be attached to the integer in python memory no attention is paid to where the integer came from the name delta is already in use and is attached to the integer its attachment is changed to the new integer
9,987
lhs delta delta int delta int delta int no longer used againthe unreferenced"left over"object is cleaned up by python' automatic garbage collection
9,988
thing + thing thing thing - thing thing thing * thing thing thing / is equivalent to thing thing thing ** thing thing * thing % thing thing the operation of modifying the value attached to name is so common that pythonand some other languageshave short-cuts in their syntax to make the operations shorter to write these operations are called "augmented assignmentsthis sort of short-cut for an operation which could already be written in the language is sometimes called "syntactic sugar
9,989
print(thingtraceback (most recent call last)file ""line in nameerrorname 'thingis not defined unknown variable thing print(thing there' one last aspect of attaching names to values hat we need to consider how do we delete the attachmentfirst of alllet' see what it looks like when we refer to name that isn' known to the system the error message is quite straightforwardname 'thingis not defined if we then create the name and attach it to valuethe integer in this examplewe can then use the name without error message
9,990
print(thing known variable del thing print(thingtraceback (most recent call last)file ""line in nameerrorname 'thingis not defined unknown variable to delete the attachment we use the python command "delthe command del thing returns us to the state where the name is no longer known you can delete multiple names with the slightly extended syntax del thing thing thing this is equivalent to del thing del thing del thing but slightly shorter
9,991
assignment thing thing deletion del thing strictly right to left thing thing nd +etc "syntactic sugar st thing +
9,992
python sqrt py number we have to write sqrt py firstthe maths thenthe python we now have enough to make start on "real programmingwe will need some more python elements but we can meet them as we need them rather than up front we are going to write program that prompts for number and then calculates and prints out its square root first we will review the maths of calculating square roots so that we know what we are coding then we will do it in python
9,993
too small for too large for "interval of uncertainty the technique we are going to use is called "bisectionif you know this technique you can relax for the next few slides please don' snore we are going to go through it by hand for few iterations because when we come to implement it in python it is important that any confusion is due to the pythonand not the maths the python is implementing the trick is to identify range of values that must contain the actual value of that iswe identify lower bound that is less than and an upper bound that is greater than we then have some way (which we will explain in the following slidesto improve that estimate by reducing the length of that interval of uncertainty to be precisewe will cut the uncertainty in half which is why the process is called "bisectionwe start by taking lower bound of = which is definitely lower than = because = = < and an upper bound of = which is definitely higher than = because = = >
9,994
( ** mid-point sowhat' the trick for halving the interval of uncertaintywe find the midpoint of the interval in this case it' obviousthe half-way point between = and = is = then we square it to find its corresponding value of in this case = =
9,995
midpoint ** so change lower bound so whatwelly= is less than = so the corresponding -valuex= makes an acceptable lower bound for the interval of uncertainty and if we change our lower bound to this value then our interval only runs from = to = with total length rather than its original length we have halved our uncertainty if we can do this trick multiple times then we will reduce the interval of uncertainty very quickly to length so small as to be irrelevant
9,996
( ** mid-point so we do it again the new mid-point lies at = this has corresponding -value of =
9,997
** so change upper bound = is greater than = so we can use the corresponding -value of = as our new upper bound now the interval of uncertainty is halved in length again to be /
9,998
( ** mid-point we find the new mid-point againx= squaring this gives the corresponding -value =
9,999
** so change lower bound = is less than = so we change the lower bound our interval of uncertainty now has length /