Transcript
the following content is provided under a Creative Commons license your support will help MIT open courseware continue to offer highquality educational resources for free to make a donation or view additional materials from hundreds of MIT courses visit MIT opencourseware at ocw.mit.edu all right let's get started everyone so good afternoon welcome to the second lecture of 601 and also of 600 so as always if you'd like to follow along with the lecture with the lectures please go ahead and download the slides and the code that um that I'll provide uh at least an hour before class every day all right so quick recap of what we did last time so last time we talked a little bit about um what a computer is and I think the main takeaway from the last lecture is really that a computer only does what it is told right so it's not going to spontaneous spontaneously make decisions on its own you as the programmer have to tell it what you want it to do by writing programs okay so we talked about uh simple objects and um these objects were of different types so we saw integers floats and booleans and then we did a couple simple operations with them today we're going to look at a different a new a new type of object called a string and then we're going to introduce some um more powerful uh um things in our programming toolbox so we're going to look at how to how to Branch within a program and how to make things how to make the computer repeat certain tasks within our program all right so let's begin by looking at strings so strings are a new object type we've seen so far integers which were whole numbers floats which were decimal numbers and we have seen uh we've seen booleans which were true and false so strings are going to be uh sequences of characters and these characters can be anything they could be letters digits uh special characters and also spaces and you tell python that you're um you're talking about a string object by enclosing it in quotation marks so in this case I'm creating an object um whose value is h e l l space t h re and python knows it's a string object because we're enclosing it in quotations they could be either double quotes or single quotes but as long as you're consistent it doesn't matter and this object we're we're um we're binding it to this variable named high and we're using that using the equal sign which is the assignment operator okay so from now on whenever we refer to this variable High Python's going to say oh I know what the value is and it's that string of characters so we're going to learn about two things that you can do on strings today two operations one is to concatenate them and concatenation is really just a fancy word for using this plus operator which means put the strings together so I have this original um variable named high and I create a new variable called name and in it I'm going to assign I'm going to assign the string a Ana to the variable name and when I use the plus operator in between high and name those two variables python is going to look at the values of those two and it's going to just put them together okay I'm going to switch to Sky to spider and this is just that example from the uh from the slides so let's see what happens so I have the variable um High the variable name and I'm just concatenating those two together and then I'm going to print that out so if I I run the code notice it prints out hello there Anna right there's no space and there's no space because the concatenation operator the plus uh doesn't add any spaces implicitly so again another example of just computer just doing what it's told if we want to add a space we'd have to actually insert the space manually so that's this line here line eight and in this line we're concatenating the VAR the the value of the variable High with a space notice we're putting it in quotation marks just a space and then with name so if we go ahead and print that value notice this was that garbage greeting there and now we have a proper greeting right another so that's the concatenation um between strings and then the other thing we're going to look at uh related to Strings is the star operator so that's this one here on line 10 so python allows you to use the star operator which is stands for multiplication between a string and a number and when you do that python interpret interprets it as repeat that string that many number of times so in this case I'm creating a silly greeting and I'm concatenating the value of high which is hello there with the space plus the name so notice here I'm using parentheses to tell python do this operation first and then multiply whatever the result of this is by three okay so if I print that out it's going to multiply the space with my name three times and it's going to concatenate that with hello there so that's exactly what it printed out there last lecture we talked a little bit about about print today I'm going to talk uh about some nuances related to print so you use print to interact with the user um it's cool to write programs that print things out to the user so the keyword here being print and then you put parentheses after print and in the parentheses you put in whatever you want to show the user so in this little program I have I create a variable named X I assign it the value one and then I print one here I'm casting so I'm taking the number one the integer one and I'm casting it to a string and you'll see why in a moment so I want to bring to your attention a couple things here so in the first print I'm using commas everywhere here and then the second print I'm using plus okay so by definition if you you can use print you can use commas inside a print inside the parenthesis of print and if you use a comma Python's going to automatically add a space in between the two things that the comma is in in between the values so my fav num is is the first thing and the second thing is whatever is after the comma let's take X so if you use a comma Python's going to automatically insert a space for you okay sometimes you might want that sometimes you might not if you don't want that you can use the concatenation operation the plus and you can add all of your little bits together to create one big string if you're using commas the the items the objects in between the commas do not all have to be strings that's the plus side of using commas but the noun side is you get spaces everywhere if you use plus operator the plus side is python does exactly what you tell it to do but everything has to be a string object so my fave num is is a string object you have to convert all of your numbers to string objects and so on so if we look at spider this is the same almost the same code so here I don't have spaces anywhere so you can see that the first line here has commas everywhere so I'm going to have spaces in between every one of the things that I'm um that I'm printing out this line here is sort of a combination between Comm commas and concatenation so depending on where I use the comma I'm going to have an extra space and this line here just has concatenation everywhere okay so if I run this notice this very first line added spaces everywhere in between all my objects the second one added spaces somewhere and you can sort of Trace through and see exactly where the spaces were added and the last line here didn't add spaces anywhere okay okay so printing things out to the console is nice but the second part of sort of writing an interactive program is getting input from the user and that's that's a more interesting part so if you've done problem set zero you might have sort of already tried to understand this on your own but here we are so the way you get input from the user is using this command function called input and inside the parentheses you type in whatever you'd like to prompt the user with so in this case in my example here I have input and then here I said type anything so the user is going to see this text here and then the program is just going to stop and it's going to wait for the user to type in something and hit enter as soon as the user types in enter whatever the user types in becomes a string okay if the user types in a number for example that becomes the string that number okay so everything that user types in is going to be made as a string in this line right here whatever the user types in becomes a string and we're going to bind that string object to this variable named uh called text okay so now further in my program I can do whatever I want with this variable text in this case I'm going to print five star text okay so if the user for example gave me ha I'm going to print ha five times if the user gave me five what do you think the user what do you think is going to be printed out 25 or five five times great yes exactly five five times okay often times you don't want to work with numbers as strings right you want to work with numbers as numbers right so you have to cast and we learned that last lecture you cast by just putting in this little bit right in front of the input and you can cast it to whatever type you want here I cast it to an INT but you can also cast to a float if you want to work with floats and that converts whatever the user typed in as long as it's some number that python knows how to how to convert into the number itself so in this case if the user gives me five I'm going to print out 5 * 5 instead of five five times so that's the code here so the first bit is I'm going to get the user to type in anything and I'm going to put 555 and then when I type in the number since I'm casting it I'm going to do operations with the number okay yeah question in why do you want to cast to oh uh the question is why do you want to cast to a string why do you want to cast a string to a number oh so python always whatever you whatever you type in just by default by definition of the input command python always makes it a string so if you want to work with numbers you have to explicitly tell it I'm going to work with a number so even if you give it the number five it's going to think it's the string five yeah that's just how input works the next thing it we're going to look at is ways that you can um start adding tests in your code and before you can start adding tests before you can start adding tests in your code you need to be able to do the actual tests so this is where comparison operators come in okay so here let's assume that I and J are variables okay the following comparisons are going to give you a Boolean so it's either going to say this is true or this is false so that's going to be your test so if I and J are variables you're allowed to compare ins with ins floats with floats strings with strings and you're allowed to compare ins and floats between themselves but you're not allowed to compare a string with a number in fact if you even try to do that in Python in spyer here if I try to say is the letter a greater than five I get some angry text right right here and this just tells me python doesn't understand the meaning of what how do I compare a string with a number right okay so just like in math we can do these usual comparisons we can say something's greater than something greater or equal to less than less than or equal to I'd like to bring to your attention the equality so the single equal sign is an assignment so you're taking a value and you're signing it to a variable but when you're doing the double equal sign this is the test for equality is the value of variable I the same as the value of the variable J okay and that's that's again also going to give you a Boolean either true or false and you can also test for inequality with the exclamation equal so that means is the V value of the variable I not equal to the value of the variable J true if yes false if no okay so those are comparison operators on Integer floats and strings on booleans you can do some logic operators and the simplest is just inverting so if a is a v if a is a variable that can that has a Boolean value not a is just going to invert it so if a is true then not a is false and vice versa this is a table that sort of represents what I've said here so you can do you can use and and or these are keywords in Python you can use those two keywords on variables on Boolean variables and you get the result A and B is only true if both A and B are true and A or B is only false if a and b are false okay and this is the complete table just in case you need to reference it all right so now that we have ways to do logical te Yeah question right there what does it yeah great question so what does it mean to compare string with a string with the greater than so that's just going to compare them uh lexicographically so does it come first in the alphabet so we can even test that out we can say is a greater than b and it's false so b b comes later in the alphabet than a right okay so now we have ways to do the tests so we can add um some branching to our programming toolbox now that we have ways to do tests okay this is a map of MIT I'm going to go through sort of a little example to motivate why we want to do branching in our in our um in our code and I think after this lecture you'll be able to sort of code up this algorithm that I'm going to explain so most of us see MIT as a maze I first did when I came here when I first came here obviously I signed up for the free food mailing list and MIT MIT being am maaz I had no idea where to go right what the shortest path was to free food so one way to to think about it is all I wanted to do was get to the free food a very simple algorithm to get there would be to say okay I'm going to take my right hand and I'm going to make sure that my right hand is always on a wall okay and I'm going to go around campus with my right hand always being at a wall and eventually I'll get to the where the free food is I might not there might not be any left right but I'll be there okay so the algorithm is as follows okay if my right hand always has to be on a wall then I'm going to say if there's no wall to my right side then I'm going to go right until I get to a wall Okay then if there's a wall to my right and I can go forward I'm just going to keep going forward okay if I keep going forward and there's a wall to my right in front of me I'm going to turn around and go left okay and then if there's a wall to my right in front of me and to the left then I'm going to turn around and go back so with this fairly simple algorithm I just follow the the path always keeping the wall to my right and eventually I end up where I need to be okay so notice I used just in plain English a few keywords okay if otherwise things like that so in program in we have those same constructs and those same sort of intuitive words can be used to tell python to do something or to do something else or to choose from a different um set of possibilities okay and this way we can get the computer to make decisions for us now you might be thinking well you said that computers can't make decisions on their own it's not us programmers are going to build these decisions into the program and all the computer is going to do is going to say is going to reach the decision point and say okay this is a decision point should I go left or should I go right or which one do I pick and these sort of decisions are created by you as a programmer and the computer just has to make make the decision and choose a path okay so in programming there's three sort of simple ways that you can add um control flow to your programs and that's making one decision and choosing whether to execute something or execute something else the first is the simple if okay and given a program that just linearly has statements that get executed whenever I reach an if statement you're going to check the condition the condition is going to be something that's going to get evaluated to either true or false okay so I've reached the condition here and if the condition's true then I'm going to additionally execute this extra set of Expressions but if the condition's false then I'm just going to keep going through the program and not execute that extra set of instructions okay how does python know which instructions to execute they're going to be inside this what we call code block and the code block is denoted by indentation so it's going to be everything that's indented is part of that if code block typic typically four spaces of dentation okay so that's that's how you'd write code that decides whether to execute this extra thing or not now let's say I don't just want to execute an extra thing I want to reach a condition I want to reach a point where I say I'll either go down this path or I'll do something else okay that's this right here so this if else construct says this is my code I've reached my decision Point here if the condition inside this if is true then I'm going to execute maybe this set of statements here okay but if the condition is not true then I'm not going to execute that set of statements and instead I'm going to execute under whatever else is so using this construct I'm either going to do one set of expressions or the other but never both okay and after I've executed one or the other I'm going to continue on with just the regular execution of the program all right okay so we're able to either choose one thing choose one thing or another but what if we want to have uh more than one choice so if some number is equal to zero I want to do this if it's equal to one I want to do this otherwi if it's equal to two I want to do this and so on that's where this last one comes in and we introduce this other keyword here called L if so that stands for short form for else if so first we check if this condition is true so we're going through our program we've reached our decision point if the condition is true we're going to execute maybe this set of instructions if the condition is not true maybe we'll check if the condition is not true we will check this next condition that's part of the L if right here and if that one's true we're going to execute a different set of instructions you can have more than one L if and depending on which one's true you're going to execute a different set of instructions and then this last else is sort of a c all where if none of the previous conditions were true then just do this this last set of Expressions so in this case you're going to choose between one of these three one of these four roots or however many you have and then when you're done making your choice you're going to execute the remaining set of instructions so the way this works is if more than one condition is true you're actually just going to enter one of them and you're going to enter the very first one that's true so you're never going to enter more than one of these code blocks you're always enter one and you enter the very the first one that's that evaluates to true so notice that we denoted code blocks using indentation and that's actually one of the things that I really like about python it sort of forces you to write pretty code and nice looking code um and just code that's very readable um and that forces you to indent everything that's a code block okay so you can easily see sort of where the flow of control is and where decision- making points are and and things like that okay so in this particular example we have one if statement here and it checks if two variables are equal and we have an if L if else and in this example we're going to enter either this code block or this one or this one depending on the variables of X and Y and we're only going to enter one code block and we'll enter the first one that that's true notice you can have nested conditionals so inside this first if we have another if here and this inner if is only going to be checked when we enter the first this outer if okay I do want to make one point though so sometimes you might forget to do the double equal sign when you do when you check when you're checking for equality and that's okay if you just use one equal sign Python's going to give you an error and it's going to say syntax error and it's going to highlight this line and then you're going to know that there's there's a there's a mistake there you should be using equality because it doesn't make sense to be using to to assign to be making an assignment inside the if okay all right so we've learned about branching and we know about conditionals let's try to apply this to uh to a little game and spoiler we won't be able to we'll have to learn about a new thing but back 1980s there was The Legend of Zelda cool graphics um where there was a scene with the Lost Woods okay oversimplification if anyone's a Zelda know D die hard fan but the basic idea was if you entered the woods you know you entered from the left to the right and then as long as you kept going right it would show you the same screen over and over again okay and the trick was you just had to go backward and then you'd exit exit the wood okay so very simple using what we know so far we could sort of code this up and we'd say something like this if the user exits right then set the background to the woods background otherwise set the background to the exit background okay now let's say the user and then and then in the else we're done let's say the user went right well you'd show them the woods background and now ask them again where do they want to go if they exit right set the background to the woods backgr otherwise set the background to the exit background and so on so you notice that there's sort of no end to this right how many time do you know do you know how many times the user might keep going right they might be really persistent right and they'll be like maybe maybe if I go a thousand times I'll get out of the woods you know or maybe a thousand one maybe so this this would probably be who knows how how deep this this nested these nested ifs okay okay so we don't know so with what we know so far we can't really code this this cute little game but enter loops and specifically a while loop so this code here that could be you know infinitely number of nested if statements deep can be Rewritten using these three lines so we say while the user exits right set the background to the woods background and with a while loop it's going to do what we tell it to do inside the loop and then it's going to check the condition again and then it's going to do what we what we say it should do inside the code block and then it's going to set the check the condition again and then when the condition as long as the condition is true it's going to keep doing that little Loop there and as soon as the condition becomes false it's going to stop doing the loop and do whatever is right after the while okay so that's basically how a while loop works we have while that's the keyword the condition is something that gets evaluated to true or false and once again we have a code block that's indented and it tells python these are the Expressions I want to do as long as the condition is true so the condition is true you evaluate every expression in the code block when you reach the end of the expression end of the code block you check the condition again if it's true still you keep doing the Expressions check again and so on so here's a little game and with these lines of code we were able you know we can code up the the Lost lwoods of uh of Zelda even worse Graphics by the way than the original Zelda is this one that I coated up here so I print out the following things you're in the L Forest go left or right and my program is going to say you know you're in the lost forest go left left or right it's going to get user input it's going to say while the user keeps typing in right show them this text and ask them again right so I'm asking them again by just saying input here again and that's it that's going to just keep getting input from the user and if the user doesn't type in right and maybe types in left you're going to exit out of this Loop and print out you got out of the last Force so I have to show you this because I spent too much time on it but I decided to improve on the code that's in the slides and I've written here ways that you guys can also improve it so if I run my code you you're in the lost forest go left or right so if I say left then yay I got out of the lost forest but if I go right then I'm stuck right I took down some trees you can see there's no more trees here I made a table and then I flipped it over okay so the expansion to this if you want to try it out I I put this in the comments here is try to use a counter okay if the user types in write the first two times just make that a sad face but if the user types in more than two times make them cut down some trees and build a table and flip it okay that's a cute little expansion if you want to test yourself to make sure you you're getting Loops okay so so far we've used while Loops to ask for user input and that's actually somewhere where it makes sense to use while Loops because you don't actually know how many times the user is going to type in something you can use y Loops to keep sort of a counter and to write code that counts something if you do that though there's two there's two things you need to take care of the first is this first line here which is sort of an initialization of this Loop counter and the second is this line here which is incrementing your Loop counter the reason why the second one's important is because let's look at our condition here so while n is less than five if you didn't have this line here you never increment n so every time through the loop you just keep printing zeros okay and you'd have an infinite loop I do want to show though what if you do have an infinite loop it's not the end of the world so I can say something like uh okay so while true print zero okay so this is going to give me an infinite Loop in my program and okay so notice it's just printing the letter P over and over again and if I let it go any longer it's going to slow down the computer so I'm going to hit control C or command C maybe and it's going to stop the program from printing okay so just in case you ever enter infinite Loops in your programs just go to the console and hit contrl C and that's going to stop it from sort of slowing down the computer okay so going back to this example I was saying that if you're using counters or variables in order to sort of count up inside the Y Loop you have to take care to initialize a count counter variable first and then to increment it otherwise you'll enter an infinite Loop that feels a little bit tedious and so there's a shortcut for doing that EX exact same thing so these four lines you can rewrite those into these two lines right here using this new type of loop called a four Loop so the for Loop says for some Loop variable in this case I named it n you can name it whatever you want in range five we're going to come back to what range means in a little bit print n okay so every time through the loop you're going to print out what the value of n is range five actually creates internally a sequence of numbers starting from zero and going to that number 5 - one so the sequence is going to be 0 1 2 3 and four the first time through the loop you're going to say n is equal to zero or internally this is what happens n gets the value zero you're going to print n then you're going to back go back to the to the top n gets the value one then you're going to go execute whatever inside so you're going to print one then you're going to increment that to the next value in the sequence you're going to print out two and so on so this is the general um look of a for Loop so we have four some uh loop variable again can be named whatever you want in range some number do a bunch of stuff and again these are part of this four Loop code block so you should indent them to tell python that these are the things that you should do okay so when you're using range some number you start out with variable getting the value zero okay with with variable having value zero you're going to execute all of these Expressions after all the expressions in the code block are done you're going to go on to the next value so one you're going to execute all these expressions with the variable being value one and then so on and so on until you go to Su num minus one that it so so using range in that way is a little bit con constraining because you're always going to get values starting from zero and ending at some num minus one okay whatever is in in the parentheses and range sometimes you might want to write programs that maybe start at a custom some value don't start at zero maybe they start at five maybe they start at minus 10 and sometimes you might want to write programs that don't go with uh don't increment the numbers by one but maybe skip every other number or go every two numbers every three numbers and so on so you can customize range to your needs the one thing you do need to give it is this stop so if you give it only one value in the parenthesis that stands for stop and by default start is going to have value zero and step is going to have the value one if you give it two things in the parentheses you're giving it start and stop so the first being start the second being stop and step gets this value of one by default and if you give it three things in the parentheses you're giving it start stop and step in that order and you're always going to start at the start value and stop at or so you're going to start at the start value and you're going to go until stop minus one so those are the the sequences of numbers so in this first code right here my sum is going to get the value zero and you're going to have a for loop we're going to start from Seven right because we're giving it two numbers and when you give it two numbers it represents start and stop with step being one so you're starting at seven if step is one the next value is eight what's the value after that if we're incrementing by one nine and since we're going until stop minus one we're not actually going to pick up on 10 okay so this Loop variable I the very first time through the loop is going to have the value seven so my sum is going to be 0 + 7 that's everything that's inside the code block the next time through the loop I gets the value eight so inside inside the for Loop my sum gets whatever the previous value was which was 7 + 8 okay the next time through the loop my sum gets the value 7 + 8 + 9 obviously replacing that with the previous value so 15 okay since we're not going through 10 that's where we stop and we're going to print out my sum which is going to be the value of 7 + 8 + 9 oh yeah oh okay yeah start do they have to be integers um that's a great question we can try that out I'm not actually sure right off just off the top of my head so you can go in spider and say um let's say in this example here in this example here so we can say 7.1 10.3 yeah so they have to be integers okay so that's that's that example and let's erase that in this particular example we have start stop and step and here we're going going every other value so we're starting at five tell me what the next value is supposed to be if we're taking every other one seven and then nine and then are we doing 11 or not excellent nice yeah so we're going to the end minus one okay so it's possible that sometimes you write code where you might want to exit out of the loop early okay you don't want to go through all of the sequences of your numbers maybe there's a condition inside there where you just want to exit the loop early inside the Y Loop maybe you want to exit the loop before the condition becomes false so that's where the break statement comes in so the break works like this it's going to as soon as python sees this break statement it's going to say okay I'm going to look at whatever Loop I'm currently in I'm not evaluating any expression after it that comes within my Loop and I'm going to immediately exit the loop so I'm going inside this while this while I'm evaluating this one expression and then I suddenly see a break expression B does not get evaluated and break is going to immediately exit out of the innermost Loop that it's in so this y Loop that has condition two that's the innermost Loop that the brake is found found in so we're going to exit out of this innermost Loop here and we're evaluating expression C and notice we're evaluating expression C because it's expression C is part of the outer while loop it's at the same level as this one and these ones are part of the inner while loop okay okay last thing I want to say is just a little bit of a comparison between four and while Loops so when would you use one or the other um this might be useful in your problem sets so for Loops you usually use when you know the number of iterations okay y Loops are very useful when for example you're getting user input and user input is unpredictable right you don't know how many times they're going to do certain task for both four and Y Loops you can end out of the loop early using the break the four Loop uses this counter it's inherent inside the for Loop a while loop you can use a counter in order you can use a while loop to count things but you must initialize the counter before the Y Loop and you have to remember to increment it within the loop otherwise wise you'll you maybe lead to an infinite Loop we've seen in uh as the very first example of of a for Loop that the while loop the for Loop could be Rewritten as a while loop but the vice versa is not necessarily true and the counter example to that is just user input so you might not know how many times you might do a certain task all right great that's uh that's all for today