Tuesday, May 24, 2022

Lec 1 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008

The following content isprovided under a Creative Commons license. Your support will help MITOpenCourseware continue to offer high-quality educationalresources for free. To make a donation, or viewadditional materials from hundreds of MIT courses, visitMIT OpenCourseware, at ocw.mit.edu . PROFESSOR: Good morning. .

Try it again. Good morning. STUDENTS: Good morning. PROFESSOR: Thank you. This is 6.00, also known asIntroduction to Computer Science and Programming. My name is Eric Grimson, I havetogether Professor John Guttag over here, we'regoing to be lecturing the course this term. .

I want to give you a heads up;you're getting some serious firepower this term. John was department head forten years, felt like a century, and in course six,I'm the current department head in course six. John's been lecturing forthirty years, roughly. All right, I'm the young guy,I've only been lecturing for twenty-five years. You can tell, I have lessgrey hair than he does. .

What I'm trying to say toyou is, we take this course really seriously. We hope you do as well. But we think it's reallyimportant for the department to help everybody learn aboutcomputation, and that's what this course is about. What I want to do today is threethings: I'm going to start– actually, I shouldn'tsay start, I'm going to do a little bit of administrivia, thekinds of things you need .

To know about how we're goingto run the course. I want to talk about the goalof the course, what it is you'll be able to do at the endof this course when you get through it, and then I wantto begin talking about the concepts and tools ofcomputational thinking, which is what we're primarily goingto focus on here. We're going to try and help youlearn how to think like a computer scientist, and we'regoing to begin talking about that towards the end of thislecture and of course .

Throughout the rest of thelectures that carry on. Right, let's startwith the goals. I'm going to give yougoals in two levels. The strategic goals are thefollowing: we want to help prepare freshmen and sophomoreswho are interested in majoring in course six toget an easy entry into the department, especially for thosestudents who don't have a lot of prior programmingexperience. If you're in that category,don't panic, you're .

Going to get it. We're going to help you rampin and you'll certainly be able to start the course sixcurriculum and do just fine and still finish on target. We don't expect everybody tobe a course six major, contrary to popular opinion,so for those are you not in that category, the second thingwe want to do is we want to help students who don't planto major in course six to feel justifiably confident intheir ability to write and .

Read small pieces of code. For all students, what we wantto do is we want to give you an understanding of the rolecomputation can and cannot play in tackling technicalproblems. So that you will come away with a sense of whatyou can do, what you can't do, and what kinds of things youshould use to tackle complex problems. And finally, we want to positionall students so that you can easily, if you like,compete for things like your .

Office and summer jobs. Because you'll have anappropriate level of confidence and competencein your ability to do computational problem solving. Those are the strategic goals. Now, this course is primarilyaimed at students who have little or no prior programmingexperience. As a consequence, we believethat no student here is under-qualified for thiscourse: you're all MIT .

Students, you're all qualifiedto be here. But we also hope that therearen't any students here who are over-qualifiedfor this course. And what do I mean by that? If you've done a lot priorprogramming, this is probably not the best course for you,and if you're in that category, I would pleaseencourage you to talk to John or I after class about what yourgoals are, what kind of experience you have, and howwe might find you a course .

That better meets your goals. Second reason we don't wantover-qualified students in the class, it sounds a little nasty,but the second reason is, an over-qualified student,somebody who's, I don't know, programmed for Google for thelast five years, is going to have an easy time in thiscourse, but we don't want such a student accidentallyintimidating the rest of you. We don't want you to feelinadequate when you're simply inexperienced. .

And so, it really is a courseaimed at students with little or no prior programmingexperience. And again, if you're not in thatcategory, talk to John or I after class, and we'll helpyou figure out where you might want to go. OK. Those are the top-levelgoals of the course. Let's talk sort of at a moretactical level, about what do we want you to knowin this course. .

What we want you to be ableto do by the time you leave this course? So here are the skills that wewould like you to acquire. Right, the first skill we wantyou to acquire, is we want you to be able to use the basictools of computational thinking to write small scaleprograms. I'm going to keep coming back to that idea,but I'm going to call it computational thinking. And that's so you can writesmall pieces of code. .

And small is not derogatoryhere, by the way, it just says the size of things you'regoing to be able to do. Second skill we want you to haveat the end of this course is the ability to use avocabulary of computational tools in order to beable to understand programs written by others. So you're going to be ableto write, you're going to be able to read. This latter skill, by the way,is incredibly valuable. .

Because you won't want to doeverything from scratch yourself, you want to be ableto look at what is being created by somebody else andunderstand what is inside of there, whether it workscorrectly and how you can build on it. This is one of thefew places where plagiarism is an OK thing. It's not bad to, if you like,learn from the skills of others in order to createsomething you want to write. .

Although we'll come backto plagiarism as a bad thing later on. Third thing we want you todo, is to understand the fundamental both capabilitiesand limitations of computations, and the costsassociated with them. And that latter statement soundsfunny, you don't think of computations havinglimits, but they do. There're some things thatcannot be computed. We want you to understandwhere those limits are. .

So you're going to beable to understand abilities and limits. And then, finally, the lasttactical skill that you're going to get out of this courseis you're going to have the ability to map scientificproblems into a computational frame. So you're going to be able totake a description of a problem and map it intosomething computational. Now if you think aboutit, boy, it sounds .

Like grammar school. We're going to teach you toread, we're going to teach you to write, we're going to teachyou to understand what you can and cannot do, and mostimportantly, we're going to try and give you the startof an ability to take a description of a problem fromsome other domain, and figure out how to map it into thatdomain of computation so you can do the reading and writingthat you want to do. OK, in a few minutes we're goingto start talking then .

About what is computation, howare we going to start building those tools, but that's what youshould take away, that's what you're going to gain outof this course by the time you're done. Now, let me take a sidebar forabout five minutes to talk about course administration, theadministrivia, things that we're going to do in the course,just so you know what the rules are. Right, so, class is two hoursof lecture a week. .

You obviously know whereand you know when, because you're here. Tuesdays and Thursdaysat 11:00. One hour of recitation a week,on Fridays, and we'll come back in a second to how you'regoing to get set up for that. And nine hours a week ofoutside-the-class work. Those nine hours are going tobe primarily working on problem sets, and all theproblems sets are going to involve programming in Python,which is the language we're .

Going to be using this term. Now, one of the things you'regoing to see is the first problem sets are pretty easy. Actually, that's probablywrong, John, right? They're very easy. And we're going to ramp up. By the time you get to the endof the term, you're going to be dealing with some fairlycomplex things, so one of the things you're going to see is,we're going to make heavy use .

Of libraries, or codewritten by others. It'll allow you to tackleinteresting problems I'll have you to write from scratch, butit does mean that this skill here is going to bereally valuable. You need to be able to read thatcode and understand it, as well as write your own. OK. Two quizzes. During the term, the dates havealready been scheduled. .

John, I forgot to look them up,I think it's October 2nd and November 4th, it'll beon the course website. My point is, go check the coursewebsite, which by the way is right there. If you have, if you know youhave a conflict with one of those quiz dates now, pleasesee John or I right away. We'll arrange somethingahead of time. But if you– The reason I'm saying that is,you know, you know that you're .

Getting married that day forexample, we will excuse you from the quiz to get married. We'll expect you come rightback to do the quiz by the way, but the– Boy, tough crowd. All right. If you have a conflict,please let us know. Second thing is, if you have anMIT documented special need for taking quizzes, please seeJohn or I well in advance. .

At least two weeksbefore the quiz. Again, we'll arrange for this,but you need to give us enough warning so that we candeal with that. OK, the quizzes are open book. This course is notabout memory. It's not how well you canmemorize facts: in fact, I think both John and I are alittle sensitive to memory tests, given our age,right John? This is not about how youmemorize things, it's about .

How you think. So they're open note,open book. It's really going to testyour ability to think. The grades for the course willbe assigned roughly, and I use the word roughly because wereserve the right to move these numbers around a littlebit, but basically in the following percentages: 55% ofyour grade comes from the problem sets, the other 45%come from the quizzes. And I should've said there's twoquizzes and a final exam. .

I forgot, that final examduring final period. So the quiz percentagesare 10%, 15%, and 20%. Which makes up the other 45%. OK. Other administrivia. Let me just look throughmy list here. First problem set, problem setzero, has already been posted. This is a really easy one. We intend it to be a reallyeasy problem set. .

It's basically to get you toload up Python on your machine and make sure you understandhow to interact with it. The first problem set will beposted shortly, it's also pretty boring– somewhat likemy lectures but not John's– and that means, you know,we want you just to get going on things. Don't worry, we're going to makethem more interesting as you go along. Nonetheless, I want to stressthat none of these problems .

Sets are intendedto be lethal. We're not using them to weed youout, we're using them to help you learn. So if you run into a problemset that just, you don't get, all right? Seek help. Could be psychiatric help,could be a TA. I recommend the TA. My point being, please comeand talk to somebody. .

The problems are set up so that,if you start down the right path, it should be prettystraight-forward to work it through. If you start down a plausiblebut incorrect path, you can sometimes find yourself stuck inthe weeds somewhere, and we want to bring you back in. So part of the goal here is,this should not be a grueling, exhausting kind of task, it'sreally something that should be helping you learnthe material. .

If you need help, ask John,myself, or the TAs. That's what we're here for. OK. We're going to run primarily apaperless subject, that's why the website is there. Please check it, that's whereeverything's going to be posted in terms of thingsyou need to know. In particular, please go to ittoday, you will find a form there that you need to fill outto register for, or sign .

Up for rather, a recitation. Recitations are on Friday. Right now, we have themscheduled at 9:00, 10:00, 11:00, 12:00, 1:00, and 2:00. We may drop one of therecitations, just depending on course size, all right? So we reserve the right,unfortunately, to have to move you around. My guess is that 9:00 is notgoing to be a tremendously .

Popular time, but maybeyou'll surprise me. Nonetheless, pleasego in and sign up. We will let you sign up forwhichever recitation makes sense for you. Again, we reserve the right tomove people around if we have to, just to balance load, but wewant you to find something that fits your schedulerather than ours. OK. Other things. .

There is no required text. If you feel exposed without atext book, you really have to have a textbook, you'll find onerecommended– actually I'm going to reuse that word, John,at least suggest it, on the course website. I don't think either of us arethrilled with the text, it's the best we've probably foundfor Python, it's OK. If you need it, it's there. But we're going to basically notrely on any specific text. .

Right. Related to that: attendancehere is obviously not mandatory. You ain't in highschool anymore. I think both of us would love tosee your smiling faces, or at least your faces,even if you're not smiling at us every day. Point I want to make about this,though, is that we are going to cover a lot of materialthat is not in the .

Assigned readings, and we dohave assigned readings associated with each oneof these lectures. If you choose not to show uptoday– or sorry, you did choose to show up today, if youchoose not to show up in future days– we'll understand,but please also understand that the TAs won'thave a lot of patience with you if you're asking a questionabout something that was either covered in thereadings, or covered in the lecture and is prettystraight forward. .

All right? We expect you to behaveresponsibly and we will as well. All right. I think the last thing I wantto say is, we will not be handing out class notes. Now this sounds like adraconian measure; let me tell you why. Every study I know of, and Isuspect every one John knows, .

About learning, stresses thatstudents learn best when they take notes. Ironically, even if theynever look at them. OK. The process of writing isexercising both halves of your brain, and it's actually helpingyou learn, and so taking notes is reallyvaluable thing. Therefore we're not goingto distribute notes. What we will distribute formost lectures is a handout .

That's mostly code examplesthat we're going to do. I don't happen to have one todaybecause we're not going to do a lot of code. We will in future. Those notes are going to makeno sense, I'm guessing, outside of the lecture,all right? So it's not just, you can swingby 11:04 and grab a copy and go off and catchsome more sleep. What we recommend is you usethose notes to take your own .

Annotations to help youunderstand what's going on, but we're not going toprovide class notes. We want you to take your ownnotes to help you, if you like, spur your ownlearning process. All right. And then finally, I want tostress that John, myself, all of the staff, our job isto help you learn. That's what we're here for. It's what we getexcited about. .

If you're stuck, if you'restruggling, if you're not certain about something,please ask. We're not mind readers, wecan't tell when you're struggling, other than sort ofseeing the expression on your face, we need your helpin identifying that. But all of the TAs, many of whomare sitting down in the front row over here, are hereto help, so come and ask. At the same time, remember thatthey're students too. And if you come and ask aquestion that you could have .

Easily answered by doing thereading, coming to lecture, or using Google, they're goingto have less patience. But helping you understandthings that really are a conceptual difficulty is whatthey're here for and what we're here for, so pleasecome and talk to us. OK. That takes care of theadministrivia preamble. John, things we add? PROFESSOR GUTTAG: Twomore quick things. .

This semester, your classis being videotaped for OpenCourseware. If any of you don't want yourimage recorded and posted on the web, you're supposed to sitin the back three rows. PROFESSOR GRIMSON:Ah, thank you. I forgot. PROFESSOR GUTTAG: –Becausethe camera may pan. I think you're all verygood-looking and give MIT a good image, so please, feelfree to be filmed. .

PROFESSOR GRIMSON: I'll turnaround, so if you want to, you know, move to the back,I won't see who moves. Right. Great. Thank you, John. PROFESSOR GUTTAG: So that, theother thing I want to mention is, recitations are alsovery important. We will be covering material inrecitations that're not in the lectures, not in thereading, and we do expect you .

To attend recitations. PROFESSOR GRIMSON: Great. Thanks, John. Any questions aboutthe administrivia? I know it's boring, but we needto do it so you know what the ground rules are. Good. OK. Let's talk about computation. .

As I said, our strategic goal,our tactical goals, are to help you think like a computerscientist. Another way of saying it is, we want to giveyou the skill so that you can make the computer do whatyou want it to do. And we hope that at the end ofthe class, every time you're confronted with some technicalproblem, one of your first instincts is going to be, “Howdo I write the piece of code that's going to helpme solve that?” So we want to help youthink like a computer .

Scientist. All right. And that, is an interestingstatement. What does it mean, to thinklike a computer scientist? Well, let's see. The primary knowledge you'regoing to take away from this course is this notion ofcomputational problem solving, this ability to think in computational modes of thought. And unlike in a lot ofintroductory courses, as a .

Consequence, having the abilityto memorize is not going to help you. It's really learning thosenotions of the tools that you want to use. What in the world doesit mean to say computational mode of thought? It sounds like a hifalutinphrase you use when you're trying to persuadea VC to fund you. Right. .

So to answer this, we reallyhave to ask a different question, a related question;so, what's computation? It's like a strangestatement, right? What is computation? And part of the reason forputting it up is that I want to, as much as possible,answer that question by separating out the mechanism,which is the computer, from computational thinking. Right. .

The artifact should not bewhat's driving this. It should be the notion of,”What does it mean to do computation?” Now, to answer that, I'm goingto back up one more level. And I'm going to pose whatsounds like a philosophy question, which is, “What isknowledge?” And you'll see in about two minutes why I'mgoing to do this. But I'm going to suggest that Ican divide knowledge into at least two categories. .

OK, and what is knowledge? And the two categories I'm goingto divide them into are declarative and imperativeknowledge. Right. What in the world is declarativeknowledge? Think of it as statementsof fact. It's assertions of truth. Boy, in this political season,that's a really dangerous phrase to use, right? .

But it's a statement of fact. I'll stay away from thepolitical comments. Let me give you anexample of this. Right. Here's a declarativestatement. The square root of x is that ysuch that y squared equals x, y's positive. You all know that. But what I want you tosee here, is that's a .

Statement of fact. It's a definition. It's an axiom. It doesn't help youfind square roots. If I say x is 2, I want to know,what's the square root of 2, well if you're enough ofa geek, you'll say 1.41529 or whatever the heck it is, but ingeneral, this doesn't help you find the square root. The closest it does is it wouldlet you test. You know, .

If you're wandering throughHarvard Square and you see an out-of-work Harvard grad,they're handing out examples of square roots, they'll giveyou an example and you can test it to see, is thesquare root of 2, 1.41529 or whatever. I don't even get laughs atHarvard jokes, John, I'm going to stop in a secondhere, all right? All right, so what am Itrying to say here? It doesn't — yeah, exactly. .

We're staying away from that,really quickly, especially with the cameras rolling. All right. What am I trying to say? It tells you how you might testsomething but it doesn't tell you how to. And that's what imperativeknowledge is. Imperative knowledgeis a description of how to deduce something. .

So let me give you anexample of a piece of imperative knowledge. All right, this is actually avery old piece of imperative knowledge for computing squareroots, it's attributed to Heron of Alexandria, although Ibelieve that the Babylonians are suspected of knowingit beforehand. But here is a piece ofimperative knowledge. All right? I'm going to start with a guess,I'm going to call it g. .

And then I'm going to say, if gsquared is close to x, stop. And return g. It's a good enough answer. Otherwise, I'm going to get anew guess by taking g, x over g, adding them, anddividing by two. Then you take the averageof g and x over g. Don't worry about how cameabout, Heron found this out. But that gives me a new guess,and I'm going to repeat. That's a recipe. .

That's a descriptionof a set of steps. Notice what it has, it has abunch of nice things that we want to use, right? It's a sequence of specificinstructions that I do in order. Along the way I have some tests,and depending on the value of that test, I may changewhere I am in that sequence of instructions. And it has an end test,something that tells me when .

I'm done and whatthe answer is. This tells you how tofind square roots. it's how-to knowledge. It's imperative knowledge. All right. That's what computationbasically is about. We want to have ways ofcapturing this process. OK, and that leads now to aninteresting question, which would be, “How do I build amechanical process to capture .

That set of computations?” SoI'm going to suggest that there's an easy way to do it– I realized I did the boards inthe wrong order here– one of the ways I could do it is, youcould imagine building a little circuit to do this. If I had a couple of elements ofstored values in it, I had some wires to move thingsaround, I had a little thing to do addition, little thingto do division, and a something to do the testing, Icould build a little circuit .

That would actually dothis computation. OK. That, strange as it sounds, isactually an example of the earliest computers, because theearliest computers were what we call fixed-programcomputers, meaning that they had a piece of circuitrydesigned to do a specific computation. And that's what they would do:they would do that specific computation. .

You've seen thesea lot, right? A good example of this:calculator. It's basically an example ofa fixed-program computer. It does arithmetic. If you want play video gameson it, good luck. If you want to do wordprocessing on it, good luck. It's designed to doa specific thing. It's a fixed-program computer. In fact, a lot of the otherreally interesting early ones .

Similarly have this flavor, togive an example: I never know how to pronounce this,Atanasoff, 1941. One of the earliestcomputational things was a thing designed by a guy namedAtanasoff, and it basically solved linear equations. Handy thing to do if you'redoing 1801, all right, or 1806, or whatever you wantto do those things in. All it could do, though, wassolve those equations. One of my favorite examples ofan early computer was done by .

Alan Turing, one of the greatcomputer scientists of all time, called the bombe, whichwas designed to break codes. It was actually used duringWWII to break German Enigma codes. And what it was designedto do, was to solve that specific problem. The point I'm trying to make is,fixed-program computers is where we started, but it doesn'treally get us to where we'd like to be. .

We want to capture this ideaof problem solving. So let's see howwe'd get there. So even within this frameworkof, given a description of a computation as a set of steps,in the idea that I could build a circuit to do it, let mesuggest for you what would be a wonderful circuit to build. Suppose you could build acircuit with the following property: the input to thiscircuit would be any other circuit diagram. .

Give it a circuit diagram forsome computation, you give it to the circuit, and that circuitwould wonderfully reconfigure itself to act likethe circuits diagram. Which would mean, it couldact like a calculator. Or, it could act likeTuring's bombe. Or, it could act like asquare root machine. So what would that circuitlook like? You can imagine these tinylittle robots wandering around, right? .

Pulling wires and pullingout components and stacking them together. How would you build a circuitthat could take a circuit diagram in and make a machineact like that circuit? Sounds like a neat challenge. Let me change thegame slightly. Suppose instead, I want amachine that can take a recipe, the description of asequence of steps, take that as its input, and then thatmachine will now act like what .

Is described in that recipe. Reconfigure itself, emulate it,however you want to use the words, it's going tochange how it does the computation. That would be cool. And that exists. It's called an interpreter. It is the basic heartof every computer. What it is doing, is saying,change the game. .

This is now an example of astored-program computer. What that means, in astored-program computer, is that I can provide to thecomputer a sequence of instructions describing theprocess I want it to execute. And inside of the machine, andthings we'll talk about, there is a process that will allowthat sequence to be executed as described in that recipe,so it can behave like any thing that I can describein one of those recipes. All right. .

That actually seems like areally nice thing to have, and so let me show you what thatwould basically look like. Inside of a stored-programcomputer, we would have the following: we have a memory,it's connected to two things; control unit, in what's calledan ALU, an arithmetic logic unit, and this can take ininput, and spit out output, and inside this stored-programcomputer, excuse me, you have the following: you have asequence of instructions. And these all getstored in there. .

Notice the difference. The recipe, the sequence ofinstructions, is actually getting read in, and it'streated just like data. It's inside the memory of themachine, which means we have access to it, we can change it,we can use it to build new pieces of code, as well aswe can interpret it. One other piece that goesinto this computer– I never remember where to putthe PC, John, control? ALU? .

Separate? I'll put it separate–you have a thing called a program counter. And here's the basisof the computation. That program counter points tosome location in memory, typically to the firstinstruction in the sequence. And those instructions, by theway, are very simple: they're things like, take the value outof two places in memory, and run them through themultiplier in here, a little .

Piece of circuitry, andstick them back into someplace in memory. Or take this value out ofmemory, run it through some other simple operation, stickit back in memory. Having executed thisinstruction, that counter goes up by one and we moveto the next one. We execute that instruction,we move to the next one. Oh yeah, it looks a wholelot like that. Some of those instructions willinvolve tests: they'll .

Say, is something true? And if the test is true, it willchange the value of this program counter to point tosome other place in the memory, some other point in thatsequence of instructions, and you'll keep processing. Eventually you'll hopefullystop, and a value gets spit out, and you're done. That's the heartof a computer. Now that's a slightmisstatement. .

The process to control it isintriguing and interesting, but the heart of the computer issimply this notion that we build our descriptions, ourrecipes, on a sequence of primitive instructions. And then we have aflow of control. And that flow of control iswhat I just described. It's moving through a sequenceof instructions, occasionally changing where we areas we move around. OK. .

The thing I want you to takeaway from this, then, is to think of this as, this is,if you like, a recipe. And that's really whata program is. It's a sequence ofinstructions. Now, one of things I lefthanging is, I said, OK, you build it out of primitives. So one of the questions is,well, what are the right primitives to use? And one of the things that wasuseful here is, that we .

Actually know that the set ofprimitives that you want to use is very straight-forward. OK, but before I do that, let medrive home this idea of why this is a recipe. Assuming I have a set ofprimitive instructions that I can describe everything on, Iwant to know what can I build. Well, I'm going to do the sameanalogy to a real recipe. So, real recipe. I don't know. .

Separate six eggs. Do something. Beat until the– sorry,beat the whites until they're stiff. Do something until anend test is true. Take the yolks and mix them inwith the sugar and water– No. Sugar and flour I guess isprobably what I want, sugar and water is not going to doanything interesting for me .

Here– mix them intosomething else. Do a sequence of things. A traditional recipe actuallyis based on a small set of primitives, and a good chefwith, or good cook, I should say, with that set ofprimitives, can create an unbounded number ofgreat dishes. Same thing holds truein programming. Right. Given a fixed set of primitives,all right, a good .

Programmer can programanything. And by that, I mean anythingthat can be described in one of these process, you cancapture in that set of primitives. All right, the question is, asI started to say, is, “What are the right primitives?” Sothere's a little bit of, a little piece of historyhere, if you like. In 1936, that same guy, AlanTuring, showed that with six simple primitives, anything thatcould be described in a .

Mechanical process, it'sactually algorithmically, could be programmed just usingthose six primitives. Think about that for a second. That's an incrediblestatement. It says, with six primitives,I can rule the world. With six primitives, Ican program anything. A couple of really interestingconsequences of that, by the way, one of them is, it says,anything you can do in one programming language,you can do in .

Another programming language. And there is no programminglanguage that is better– well actually, that's not quite true,there are some better at doing certain kinds of things–but there's nothing that you can do in C thatyou can't do in Fortran. It's called Turingcompatibility. Anything you can do with one,you can do with another, it's based on that fundamentalresult. OK. .

Now, fortunately we're not goingto start with Turing's six primitives, this would bereally painful programming, because they're down at thelevel of, “take this value and write it onto this tape.” Firstof all, we don't have tapes anymore in computers, andeven if we did, you don't want to be programmingat that level. What we're going to see withprogramming language is that we're going to use higher-levelabstracts. A broader set of primitives,but nonetheless the same .

Fundamental thing holds. With those six primitives,you can do it. OK. So where are we here? What we're saying is, in orderto do computation, we want to describe recipes, we want todescribe this sequence of steps built on some primitives,and we want to describe the flow of controlthat goes through those sequence of stepsas we carry on. .

So the last thing we need beforewe can start talking about real programmingis, we need to describe those recipes. All right, And to describethe recipes, we're going to want a language. We need to know not only whatare the primitives, but how do we make things meaningfulin that language. Language. There we go. .

All right. Now, it turns out there are– I don't know, John, hundreds? Thousands? Of programming languages? At least hundreds– ofprogramming languages around. PROFESSOR JOHN GUTTAG:[UNINTELLIGIBLE] PROFESSOR ERIC GRIMSON: True. Thank you. .

You know, they allhave, you know, their pluses and minuses. I have to admit, in my careerhere, I think I've taught in at least three languages, Isuspect you've taught more, five or six, John? Both of us have probablyprogrammed in more than those number of languages, at leastprogrammed that many, since we taught in those languages. One of the things youwant to realize is, .

There is no best language. At least I would argue that,I think John would agree. We might both agree we haveour own nominees for worst language, there aresome of those. There is no best language. All right? They all are describingdifferent things. Having said that, some of themare better suited for some things than others. .

Anybody here heard of MATLABMaybe programmed in MATLAB? It's great for doing things withvectors and matrices and things that are easily capturedin that framework. But there's some thingsthat are a real pain to do in MATLAB. So MATLAB's great forthat kind of thing. C is a great language forprogramming things that control data networks,for example. I happen to be, and Johnteases me about this .

Regularly, I'm an old-time Lispprogrammer, and that's how I was trained. And I happen to like Lisp andScheme, it's a great language when you're trying to deal withproblems where you have arbitrarily structureddata sets. It's particularlygood at that. So the point I want to makehere is that there's no particularly best language. What we're going to do is simplyuse a language that .

Helps us understand. So in this course, thelanguage we're going to use is Python. Which is a pretty new language,it's growing in popularity, it has a lot ofthe elements of some other languages because it's morerecent, it inherits things from it's pregenitors,if you like. But one of the things I want tostress is, this course is not about Python. .

Strange statement. You do need to know how to useit, but it's not about the details of, where do thesemi-colons go in Python. All right? It's about using it to think. And what you should take awayfrom this course is having learned how to design recipes,how to structure recipes, how to do things in modesin Python. Those same toolseasily transfer .

To any other language. You can pick up another languagein a week, couple of weeks at most, once youknow how to do Python. OK. In order to talk about Pythonand languages, I want to do one last thing to set the stagefor what we're going to do here, and that's to talkabout the different dimensions of a language. And there're three Iwant to deal with. .

The first one is, whetherthis is a high-level or low-level language. That basically says,how close are you the guts of the machine? A low-level language, we usedto call this assembly programming, you're down at thelevel of, your primitives are literally moving pieces ofdata from one location of memory to another, througha very simple operation. A high-level language, thedesigner has created a much .

Richer set of primitivethings. In a high-level language, squareroot might simply be a primitive that you can use,rather than you having to go over and code it. And there're trade-offsbetween both. Second dimension is, whetherthis is a general versus a targeted language. And by that I mean, do the setof primitives support a broad range of applications, or isit really aimed at a very .

Specific set of applications? I'd argue that MATLAB isbasically a targeted language, it's targeted at matrices andvectors and things like that. And the third one I want topoint out is, whether this is an interpreted versusa compiled language. What that basically saysis the following: in an interpreted language, you takewhat's called the source code, the thing you write, it may gothrough a simple checker but it basically goes to theinterpreter, that thing inside .

The machine that's going tocontrol the flow of going through each one ofthe instructions, and give you an output. So the interpreter is simplyoperating directly on your code at run time. In a compiled language, you havean intermediate step, in which you take the source code,it runs through what's called a checker or a compileror both, and it creates what's called object code. .

And that does two things: one,it helps catch bugs in your code, and secondly it oftenconverts it into a more efficient sequence ofinstructions before you actually go off and run it. All right? And there's trade-offsbetween both. I mean, an interpreted languageis often easier to debug, because you can still seeyour raw code there, but it's not always as fast. Acompiled language is usually .

Much faster in termsof its execution. And it's one of the things youmay want to trade off. Right. In the case of Python, it'sa high-level language. I would argue, I think Johnwould agree with me, it's basically a general-purposelanguage. It happens to be better suitedfor manipulating strings than numbers, for example,but it's really a general-purpose language. .

And it's primarily– I shouldn't say primarily, itis an interpreted language. OK? As a consequence, it's not asgood as helping debug, but it does let you– sorry, that's thewrong way of saying– it's not as good at catching somethings before you run them, it is easier at some timesin debugging as you go along on the fly. OK. .

So what does Python look like? In order to talk about Python–actually, I'm going to do it this way– we needto talk about how to write things in Python. Again, you have to let me backup slightly and set the stage. Our goal is to build recipes. You're all going to begreat chefs by the time you're done here. All right? .

Our goal is to take problems andbreak them down into these computational steps, thesesequence of instructions that'll allow us to capturethat process. To do that, we need to describe:not only, what are the primitives, but how do wecapture things legally in that language, and interactwith the computer? And so for that, weneed a language. We're about to start talkingabout the elements of the language, but to do that, wealso need to separate out one .

Last piece of distinction. Just like with a naturallanguage, we're going to separate out syntaxversus semantics. So what's syntax? Syntax basically says, what arethe legal expressions in this language? Boy, my handwriting isatrocious, isn't it? There's a English sequenceof words. It's not since syntacticallycorrect, right? .

It's not a sentence. There's no verb in thereanywhere, it's just a sequence of nouns. Same thing in our languages. We have to describe how do youput together legally formed expressions. OK? And as we add constructs to thelanguage, we're going to talk about. .

Second thing we want to talkabout very briefly as we go along is the semanticsof the language. And here we're going to breakout two pieces; static semantics and full semantics. Static semantics basicallysays which programs are meaningful. Which expressions make sense. Here's an English sentence. It's syntactically correct. .

Right? Noun phrase, verb,noun phrase. I'm not certain it's meaningful,unless you are in the habit of giving yourfurniture personal names. What's the point? Again, you can have things thatare syntactically legal but not semantically meaningful,and static semantics is going to be a wayof helping us decide what expressions, what pieces ofcode, actually have real .

Meaning to it. All right? The last piece of it is, inaddition to having static semantics, we have sortof full semantics. Which is, what doesthe program mean? Or, said a different way,what's going to happen when I run it? That's the meaning ofthe expression. That's what you want. .

All right? You want to know, what's themeaning of this piece of code? When I run it, what'sgoing to happen? That's what I want to build. The reason for pulling this outis, what you're going to see is, that in most languages,and certainly in Python– we got lots of helphere– all right, Python comes built-in with something thatwill check your static, sorry, your syntax for you. .

And in fact, as a sidebar, ifyou turn in a problem set that is not syntactically correct,there's a simple button that you push that will checkyour syntax. If you've turned in a programthat's not syntactically correct, the TAs giveyou a zero. Because it said you didn't eventake the time to make sure the syntax is correct. The system will helpyou find it. In Python, it'll find it,I think one bug at .

A time, right John? It finds one syntax error ata time, so you have to be a little patient to do it,but you can check that the syntax is right. You're going to see that weget some help here on the static semantics, and I'm goingto do an example in a second, meaning that the system,some languages are better than others on it, but itwill try and help you catch some things that are notsemantically correct .

Statically. In the case of Python, it doesthat I think all at run time. I'm looking to you again,John, I think there's no pre-time checks. Its– sorry? PROFESSOR JOHN GUTTAG:[UNINTELLIGIBLE] PROFESSOR ERIC GRIMSON:There is some. OK. Most of them, I think though,are primarily caught at run .

Time, and that's a little bitof a pain because you don't see it until you go and run thecode, and there are some, actually we're going to see anexample I think in a second where you find it, but youdo get some help there. The problem is, things that youcatch here are actually the least worrisome bugs. They're easy to spot, you can'trun the program with them there, so you're not goingto get weird answers. Not everything is goingto get caught in .

Static semantics checking. Some things are going toslide through, and that's actually a bother. It's a problem. Because it says, your programwill still give you a value, but it may not be what youintended, and you can't always tell, and that may propagateit's way down through a whole bunch of other computationsbefore it causes some catastrophic failure. .

So actually, the problem withstatic semantics is you'd like it to catch everything, youdon't always get it. Sadly we don't getmuch help here. Which is where we'd like it. But that's part of your job. OK. What happens if you actuallyhave something that's both syntactically correct, andappears to have correct static semantics, and you run it? .

It could run and give you theright answer, it could crash, it could loop forever, it couldrun and apparently give you the right answer. And you're not always goingto be able to tell. Well, you'll know when itcrashes, that doesn't help you very much, but you can'talways tell whether something's stuck in an infiniteloop or whether it's simply taking a longtime to compute. You'd love to have a system thatspots that for you, but .

It's not possible. And so to deal withthis last one, you need to develop style. All right? Meaning, we're going to try tohelp you with how to develop good programming style, but youneed to write in a way in which it is going to be easyfor you to spot the places that cause those semanticbugs to occur. All right. .

If that sounds like a reallylong preamble, it is. Let's start with Python. But again, my goal here is tolet you see what computation's about, why we need to do it,I'm going to remind you one last time, our goal is tobe able to have a set of primitives that we combineinto complex expressions, which we can then abstract totreat as primitives, and we want to use that sequence ofinstructions in this flow of control computing, in orderto deduce new information. .

That imperative knowledge thatwe talked about right there. So I'm going to start today,we have about five or ten minutes left, I think, inorder– sorry, five minutes left– in order to do thiswith some beginnings of Python, and we're going to pickthis up obviously, next time, so; simple partsof Python. In order to create any kinds ofexpressions, we're going to need values. Primitive data elements. .

And in Python, we have two tostart with; we have numbers, and we have strings. Numbers is what you'd expect. There's a number. There's another number. All right? Strings are captured in Pythonwith an open quote and some sequence of characters followedby a closed quote. Associated with every datatype in Python is a type, .

Which identifies the kindof thing it is. Some of these are obvious. Strings are just a typeon their own. But for numbers, for example,we can have a variety of types. So this is something thatwe would call an integer, or an INT. And this is somethingwe would call a floating point, or a float. .

Or if you want to think ofit as a real number. And there's some othersthat we can see. We're going to build up thistaxonomy if you like, but the reason it's relevant is,associated with each one of those types is a set ofoperators that expect certain types of input in orderto do their job. And given those types of input,will get back output. All right. In order to deal with this, letme show you an example, .

And I hope that comesup, great. What I have here is a Pythonshell, and I'm going to just show you some simple examplesof how we start building expressions. And this'll lead into whatyou're going to see next time as well as what you'regoing to do tomorrow. So. Starting with the shell, Ican type in expressions. Actually, let me back upand do this in video. .

I can type in a number, I getback a number, I can type in a string, I get back the string. Strings, by the way, can havespaces in them, they can have other characters, it's simplya sequence of things, and notice, by the way, that thestring five– sorry, the string's digit five digittwo is different than the number 52. The quotes are around themto make that distinction. We're going to seewhy in a second. .

What I'm doing, by the way, hereis I'm simply typing in expressions to thatinterpreter. It's using its set of rules todeduce the value and print them back out. Things I might like to do inhere is, I might like to do combinations of thingswith these. So we have associated withsimple things, a set of operations. So for numbers, we have thethings you'd expect, the .

Arithmetics. And let me show you someexamples of that. And actually, I'm going to doone other distinction here. What I typed in, things like–well, let me start this way– there's an expression. And in Python the expressionis, operand, operator, operand, when we're doing simpleexpressions like this, and if I give it to theinterpreter, it gives me back exactly what you'd expect,which is that value. .

OK? The distinction I'm going tomake is, that's an expression. The interpreter is goingto get a value for it. When we start buildingup code, we're going to use commands. Or statements. Which are actually things thattake in a value and ask the computer to do somethingwith it. So I can similarly do this,which is going to look strange .

Because it's going to give methe same value back out, but it actually did a slightlydifferent thing. And notice, by the way, when Ityped it how print showed up in a different color? That's the Python saying, thatis a command, that is a specific command to get thevalue of the expression and print it back out. When we start writing code,you're going to see that difference, but for now, don'tworry about it, I just want to .

Plant that idea. OK. Once we've got that, wecan certainly, though, do things like this. Notice the quotes around it. And it treats it as a string,it's simply getting me back the value of that string,52 times 7, rather than the value of it. Now, once we've got that, wecan start doing things. .

And I'm going to use printhere– if I could type, in order to just to get into that,I can't type, here we go– in order to getinto the habit. I can print out a string. I can print out– Ah!– Here's a first exampleof something that caught one of my things. This is a staticsemantic error. .

So what went on here? I gave it an expression thathad an operand in there. It expected arithmetic types. But I gave two strings. And so it's complaining at me,saying, you can't do this. I don't know how to taketwo strings and multiply them together. Unfortunately– now John you maydisagree with me on this one– unfortunately in Pythonyou can, however, .

Do things like this. What do you figure that'sgoing to do? Look legal? The string three timesthe number three? Well it happens to give methree threes in a row. I hate this. I'm sorry, John, I hate this. Because this is overloading thatmultiplication operator with two different tasks. .

It's saying, if you giveme two numbers, I'll do the right thing. If you give me a number anda string, I'm going to concatenate them together,it's really different operations, but nonetheless,it's what it's going to do. STUDENT: [UNINTELLIGIBLE] PROFESSOR ERIC GRIMSON:There you go. You know, there will be arebuttal phase a little later on, just like with the politicaldebates, and he .

Likes it as a feature, I don'tlike it, you can tell he's not a Lisp programmer and I am. All right. I want to do just a couplemore quick examples. Here's another one. Ah-ha! Give you an exampleof a syntax error. Because 52A doesn'tmake sense. And you might say, wait aminute, isn't that a string, .

And the answer's no, I didn'tsay it's a string by putting quotes around it. And notice how the machineresponds differently to it. In this case it says, this isa syntax error, and it's actually highlighting whereit came from so I can go back and fix it. All right. Let's do a couple of othersimple examples. All right? .

I can do multiplication. I've already seen that. I can do addition. Three plus five. I can take something to a power,double star, just take three to the fifth power. I can do division, right? Whoa. Right? .

Three divided by five is zero? Maybe in Bush econom– no, I'mnot going to do any political comments today, I will notsay that, all right? What happened? Well, this is one ofthe places where you have to be careful. It's doing integer division. So, three divided by fiveis zero, with a remainder of three. .

So this is the correct answer. If I wanted to get full, realdivision, I should make one of them a float. And yes, you can look at thatand say, well is that right? Well, up to some level ofaccuracy, yeah, that's .6 is what I'd like to get out. All right. I can do other things. In a particular, I have similaroperations on strings. .

OK, I can certainly print outstrings, but I can actually add strings together, and justas you saw, I can multiply strings, you can kind of guesswhat this is going to do. It is going to merge themtogether into one thing. I want– I know I'm running you slightlyover, I want to do one last example, it's, I alsowant to be able to do, have variables to store things. And to do that, in this it says,if I have a value, I .

Want to keep it around,to do that, I can do things like this. What does that statement do? It says, create a name for avariable– which I just did there, in fact, let me type itin– mystring, with an equal sign, which is saying, assign orbind to that name the value of the following expression. As a consequence, Ican now refer to that just by its name. .

If I get the value of mystring,there it is, or if I say, take mystring and add to itthe string, mylastname, and print it back out. So this is the firststart of this. What have we done? We've got values, numbersand strings. We have operations toassociate with them. I just threw a couple up here. You're going to get a chanceto explore them, and you'll .

See not only are there thestandard numerics for strings, there are things like lengthor plus or other things you can do with them. And once I have values, I wantto get a hold of them so I can give them names. And that's what I just didwhen I bound that. I said, use the name mystringto be bound to or have the value of Eric, so I can referto it anywhere else that I want to use it. .

And I apologize for taking youover, we'll come back to this next time, please go to thewebsite to sign up for recitation for tomorrow.

RELATED ARTICLES

Most Popular