# 4. Decomposition, Abstraction, and Functions

**Channel:** MIT OpenCourseWare
**Source:** https://www.youtube.com/watch?v=MjbuarJ7SE0
**Transcript page:** https://www.withtranscript.ai/video/MjbuarJ7SE0

## Chapters

- 0:00 — Chapter 1 (0:00)
- 8:29 — Chapter 2 (8:29)
- 14:22 — Chapter 3 (14:22)
- 23:31 — Chapter 4 (23:31)
- 25:47 — Chapter 5 (25:47)
- 29:47 — Chapter 6 (29:47)
- 39:36 — Chapter 7 (39:36)

## Transcript

**[0:00]:** 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

**[0:31]:** all right everyone let's get started all right good afternoon on this rainy rainy sad afternoon so I'm glad we're inside though okay so lecture four of 6 triple1 and 600 quick quick recap of what we did last time so last time we did a little bit more string manipulations and then we saw how you can use for Loops over strings directly right so instead of having four Loops that iterate over uh range so 0 1 2 3 4 and so on you saw that it was more powerful to sometimes use for Loops that iterate over um over string objects directly so that was the first half of the lecture in the second half we started looking at different ways that you can Implement uh um the different different implementations to the same problem so we saw the problem of finding the cube root and we saw some uh implementations we saw the guess and check

**[1:27]:** method and the approximation method and then we looked at what I thought was the most powerful method which was the bisection method and this one if you remember I played a game with someone in the audience where I got uh where I guessed a number between zero and 100 and we saw that I was able to guess that number really really quickly right using the bisection method and that's the one that that's the method that you're going to implement that you are currently implementing in your problem set okay so today uh so that that that sort of um um that sort of finishes introduction to some of the more basic mechanisms in Python and today we're going to talk about how to structure your programs such that you write nice coherent code reusable code by hiding some away some of the details in your code okay and to do that we're going to look at

**[2:19]:** these things called functions all right so just stepping back and sort of getting a highlevel view of how we write the code so far okay so so far the way uh the way that you've been writing code for your programs is you know you open a file you type some code to solve a particular problem given like in your problem sets um each file contains some piece of code you know you have sequences of instructions that contain maybe you know assignments Loops conditionals and so on and so on but really you have one file that contains each code and you write everything in that in that particular file right but this is okay for smaller for smaller problems that we've been seeing so far but when you're starting to write large pieces of code it's going to get really messy really quickly okay so think about if you're you know you want to use a

**[3:09]:** for Loop in one part of your code and you find it useful to use that same for Loop in another part of your code some point in the future as you're you know debugging your code you might want to change your original for Loop you have to figure out all the other places where you've used that type of for Loop for example so as you're scaling your uh your code you you'll find it harder to keep track of of these details okay so this is where functions will come into play in today's lecture um will help you in okay so if you want to be considered a good a good programmer and good programming style would be to not necessarily add lots and lots of lines of code but really to add more functionality to your programs okay so how many different things how many different features can your program do rather than how long

**[3:59]:** can your code be right and that'll help you later on look at your code if you need it for a future class and it'll help others if they want to look at your code later on if they find it useful okay so today we're introducing this idea of functions and functions are mechanisms to achieve decomposition and abstraction okay so these are two key words here that are going to pop up in today's lecture and also in in future lectures so before I introduce decomposition and abstraction in the context of fun functions let's first take a look at just sort of a real life example so let's take a projector right I'm using one right now quick show of hands okay if I give you all of the electronic components that are part of a projector right resistors a fan a light bulb a lens the casing you know all of the different parts in it

**[4:51]:** who here would be able to build a projector do I see a hand no oh oh yeah nice you can also lie I won't know the difference but if you can do that I'd be very impressed all right so you can't really put together a projector right another show of hands if I gave you a projector that's fully assembled okay and I gave you a computer for example who'd be able to maybe figure out within let's say an hour how to how to make them work together good fair fair bit of fair bit of the class that's perfect that's exactly the answers I was trying to get at here so none of us really know how projector works right the internals but a lot more of us know how to work a projector right just given maybe a set of basic instructions or just intuitively speaking okay so you

**[5:45]:** see the projector as sort of a black box right you don't need to know how it works in order to use it right you know maybe what inputs it might take what's it supposed to do at a high level right take the whatever is on my screen and put it up on the on the large screen there just magnify it but you don't know how it does it right how the components work together so that's the idea of abstraction right you don't need to know how the projector Works in order to use it okay that's abstraction the other half of that was decomposition okay so let's say that now given a projector I want to project a very very large image down on a very large uh stage for example this is from one of the Olympics right it's a stage of like 10 football fields something like that something massive right you could build

**[6:36]:** one projector that's able to project a very large image but that would be really expensive and you'd have to build this one projector that used for this one time right so instead what you could do is you could take a bunch of smaller projectors right and feed different inputs to each one of them and as you're feeding different inputs each one's going to show a different output and then you're going to be able to have all of these different projectors working together to solve this larger problem of projecting this really cool image on a very large stage right so that's the idea of decomposition okay you take the same the same projector feed it different inputs it does the exact same thing behind the scenes but it'll produce a different output for each one of these different inputs right so these different devices are going to work together to achieve the same common goal that's

**[7:33]:** the idea of the of decomposition so this these were I applied to the problem of you know projecting large image or or a projector in general but we can apply these exact same Concepts to programming okay so decomposition is really just the problem of creating structure in your code okay in the projector example we have separate devices working together in programming to achieve decomposition you're dividing your code into smaller modules these are going to be self-contained and you can think of them as sort of little mini programs right you feed in some input to them they do a little task and then they give you something back you know they go off and do their thing and then they give back a result okay these modules can be used to break up your code and the important thing is that they're reusable so you write a module once a little piece of code that does

**[8:29]:** something once you debug it once and then you can reuse it many many times in your code with different inputs okay benefit of this is it keeps your code organized and it keeps your code coherent okay so functions are going to be used to achieve decomposition and to create structure in our code we're going to see functions today in this lecture and in a few weeks you're going to actually see when we talk about object-oriented programming how you can achieve decomposition with classes and with classes you can create your own object types like inss and floats you can create your own object types for whatever you want but that's later okay so decomposition is creating structure new code and abstraction is is the idea of suppressing details so in the projector example remember abstraction was you didn't need to know exactly how the projector worked in order to use it and it's going to be

**[9:22]:** the same idea in programming so once you write a piece of code that does a little task you don't need to re write that piece of code many times you've written it once and you write this thing called a function specification for it or a doc string and this is a piece of text that tells anyone else who'd want to use it in the future you know other people maybe yourself it tells them how to use this function what inputs does it take what's the type of the inputs what is the function supposed to do and what is the output that you're going to get out of it right so they don't need to know exactly how you implemented the function they just need to know inputs what it does what's the output those three three things okay so these functions are then reusable chunks of code and we'll see in a few examples today's

**[10:09]:** lecture how um how to write some and how to call call functions and as we're going through today's code I want you to sort of think about functions in with two two different hats on okay the first hat is from someone who's writing the function right so in the projector example someone had to build the first projector right right someone had to know how to put all these uh components together so that's going to be you writing a function right so you need to know how to make the function work and then the other hat is you as someone as a programmer who's just using the function right you're assuming it's already been implemented correctly and now you're just using it to to do something

**[10:53]:** okay so these are some of the function characteristics and we'll see an example on the next slide so function is going to have a name you have to call it something it's going to have some parameters these are the inputs to the function you can have zero inputs or as many as you'd like function should have a dock string this is how you achieve abstraction so it's optional but highly recommended and this is how you tell other people how to use your function function has a body which is the meat and potatoes of the function right what it does and a function is going to return something it's it computes its thing and then it gives back spits back some answer okay here's an example of a function definition and a function call okay function definition is up here you know what I'll just draw it here this is the function definition up here and

**[11:50]:** this is the function call down here so remember someone has to write the function you know that that does something to begin with so this is how you write the function the first is whoops the first is going to be this DF keyword and DF stands for it tells python I'm going to define a function next is the name of the function in this case I'm calling the function isore even and the function name should really be something descriptive whereas someone who's just using this function or looking at it can pretty much tell what it's supposed to do without lot without going a lot further than that than just looking at the name okay and then in parentheses you give it any parameters also known as arguments and these parameters are the inputs to the function and then you do colon okay so this is the first line of the function definition and after this

**[12:53]:** everything that's going to be part of the function is going to be indented the next part is going to be the dock string or the specification and this is how we achieve abstraction using functions specification or the doc string starts with triple quotes and ends with triple quotes and you can sort of think about this as a multi-line comment it's just going to be text that's going to be visible to whoever uses the function and it should tell them the F the following things what are the inputs to the function what is the function supposed to do generally and what is the function going to give back to whoever called it okay the next part is going to be the body of the function we'll talk about what's inside it in the next slide and that's it that's all for the function definition defa blah blah blah indented everything inside the function okay so this

**[13:52]:** is you writing the function um definition once the function definition is written you can call the function and that's this part down here and here when you call a function you just say its name and then you give it parameters and you give it as many parameters as the function is expecting in this case only one parameter

**[14:22]:** okay so what's inside the function body you can put anything inside the function body remember think of a function as sort of a small procedure a little mini program that does something so you can do anything inside the function that you can do in in a regular program print things do mathematical operations and so on the last line is the most important part of the function though and it's this return statement that's what we call it so it's a it's a line of code that starts with return which is a keyword and then it's going to be some value okay notice this is an expression here i%c 2 is equal equal Z is an expression that's going to evaluate to some value okay and as long as there this part is something that evaluates some value it could be anything you want okay and this line here return something tells python okay after you finished

**[15:17]:** executing everything inside the function what value should I return and whoever called the function is going to get back that value and the function call it s will be replaced by that value okay so let's look at an

**[15:38]:** example I'm going to introduce the idea of scope now okay and scope just means is another word for environment okay so if if I told you that you can think of functions as little mini programs the scope of a function is going to be a completely separate environment than the environment of the main program so as soon as you make a function call behind the scenes what python says is okay I'm in the main program but I see a function call I'm going to step out of this main program I'm going to go off into this new environment I'm going to create entirely new set of variables that just exists within this environment I'm going to do some computations when I see the return I'm going to take this one return value I'm going to exit that environment and then I'm going to come back to the main program okay so as you're entering from

**[16:36]:** one scope to another you're sort of passing these values back and forth so when you're entering a scope you're passing a variable back into you're passing a variable into the function and when the function's finished you're passing a value back to whoever called it okay so once again this top part is the function definition and any arguments for the function definition are called formal parameters and they're called formal parameters because notice they don't actually have a value yet right in the function definition you're sort of writing the function assuming that in this case X is going to have some value but you don't know what it is yet you only know what value X takes when you make a function call down here so this is your function definition and then later on in your M Pro main program you might Define some V variable X is equal to three and then you make a

**[17:32]:** function call F ofx here is your function call and it says okay I'm calling f with the value three because X takes the value three and then I'm going to map three into the function the values that are passed into the function call are called actual parameters because they're going to actually have a value okay so let's step through this program this little small program and see what exactly happens behind the scenes in the scope and if you're just starting to program I think it would be highly valuable if you take a piece of paper as you're doing some of these exercises and you write down something similar to what I'm going to go through here I think it'll help a lot and you'll be able to see exactly you know step by step what variables take what values and which scope you're in okay so here we go when the program first starts we're

**[18:27]:** creating This Global scope okay it's the main program scope in the main program scope the first thing that Python's going to see is this part here DF F ofx and then some some stuff inside okay this tells python I have a function named X but I don't care what's inside the code yet I don't care what's inside the function definition yet because I haven't called the function yet right so to python it's just some code just sitting in the global scope okay so whenever you see DF you're just putting some code in there then you go on to the next line X is equal to three so in the global scope you now have also a variable X is three and then the next line Z is equal to F ofx is a function call as soon as you hit a function call you create a new scope a new environment okay so we're temporary

**[19:28]:** L leaving the global scope and sort of you know portaling into a new scope where we're going to try to figure out what this function is going to do and what it's going to return so the first thing you do is you map the parameters so X here I'm calling f ofx with three so the first thing I'm doing is I'm mapping every one of the parameters in the definition to their values so the first thing I'm doing is X gets the value three okay next line here is x equal x + 1 so we're still inside the function called f so X gets the value four we're printing this and then we're returning X so in the scope of f x is equal to 4 so we're returning that value back to whoever called it which was this function call within the global scope so this part right here F ofx which was the function call gets replaced with four so inside

**[20:28]:** the main program Z is equal to 4 okay and that's how we pass parameters into the function and we got a parameter back from the function as soon as the function returns something the scope that you were in for the function gets erased you forget about every variable that was created in there delete that scope and you're back to wherever you started calling it one warning though so what happens if there's no return statement I said that every function has to return something if you don't explicitly put a return statement python is going to add one for you you don't have to do this and it's going to actually have return none n o n e and none is the special special type uh none is a the value for a special type called nun type and it represents the absence of a value okay that not a string not not a none is not

**[21:32]:** a string not none is not a string exactly it's a special special type okay so before we go on I wanted to go through a small exercise and spider just to just to show you the difference that none and uh and printing and returning makes so here are two functions that I wrote one is is even with return that's its name so it's pretty descriptive it's pretty much the same code we saw in the slides it just has this extra little print thing it gets the remainder when uh I is Divi uh divided by two and it returns whether the remainder is equal to zero so it'll either return a true or a false a Boolean okay so my function call is this I'm saying is even with return with the uh value three when I make this function call this three three gets mapped into here this variable here so I is equal to 3 I'm going to print with return and then I'm going to say

**[22:37]:** remainder is equal to 3% 2 which comes out to Value one because there's a remainder one and I'm going to return whether one is equal to zero which is false okay so this this line here returns false but am I doing anything with a false not really it's just sort of sitting in the code here okay so this gets evalu valed to um false I'm not printing it I'm not doing any operations with it it's just sitting there so it won't show up anywhere if I want the result to show up somewhere then I have to print it so that's what this next Line's doing okay so that one should be straight uh straightforward is even with that returns a little bit trickier but not too bad I have print without return inside here and then I'm going to get a remainder um is equal to i% 2 and notice that I'm not have I

**[23:31]:** don't have any return so implicitly Python's going to add a return none for me like that you don't have to add it so when I make the function call here it's going to do the same thing except the return in this case is not going to be a Boolean it's going to be this special none right so this is going to get evaluated To None again I'm not printing it out it's just sitting there if I were to print out the result of that you'd be printing out this value none which if I run it you'll see here it just prints it out right there okay so as you're doing your next pet it's it's about functions and you're seeing these nuns popping out in some places check to make sure that you've actually returned something as opposed to just printed something inside the function right like we did here okay

**[24:29]:** all right so that's the difference and the last thing I want to mention about this is even function is um is how useful it can be so notice so this is the function um as in the slides and once you write the function once you can use it many many times in your code so here I have uh I'm using the function is even to print the numbers between 0 and 19 including and whether the number is even or odd so notice this piece of code here once I've written this function is even looks really really nice right I have four all the numbers in this range if the number I is even right this is going to return a true or false for all the numbers 0 1 2 3 4 if it's true then I'm going to print out even and otherwise I'm going to print out odd so if I run this

**[25:25]:** it's going to do this zero even one odd two even and so so on so notice using functions makes my code really nice looking right if I wasn't using functions I'd have to put these two lines somewhere inside here right and it would look a little bit

**[25:47]:** Messier so I've said this maybe once or twice before in Python everything is an object okay might not have meant anything back then but I think you're going to see what I mean using this particular example okay so if if in Python everything's an object integers are objects flots are objects even functions are objects okay so as you can pass objects as parameters back and forth as function you know as function parameters you can also pass other functions as as parameters let's see what this means so we have three function definitions here Funk a funk B and Funk C and then I have three lines of code here in my main program so I have one call to Funk a one call to Funk B and one call to Funk C let's Trace through just like in the previous example and see what exactly happens first thing I create is my Global scope and I

**[26:50]:** have three function definitions again I don't care what's in the code yet because I haven't called the functions yet okay python just knows there's these functions would these names that contain some code after these definitions I come to this line here print Funk a as soon as I make a function call I'm going to create a new scope and I'm going to hop into there okay inside Funk a I'm going to go and look at what Funk a does it doesn't take any parameters it just prints out this this this message here and then it it leaves it's done there's no return so we return none so Funk a returns none to whoever called it which was that line there so that is going to be

**[27:41]:** none next line this one right here print five plus some function call again I'm going to hop into Funk B scope and see what to do there so first I'm going to map my parameters so two whoops two gets mapped to y so inside Funk B's scope Y is going to get the value two that's the very first thing I'm doing mapping all the parameters then I'm going to print this thing here and then I'm going to return y so inside Funk b y has the value two and I'm returning two back to whoever called me okay so this is the value two and I'm going to print 5 plus 2 which is seven last one this is a tricky that popped up if you think you've got it try that exercise but otherwise follow along print funky Funk a okay so I see that I am going to enter Funk C's scope so I'm

**[28:45]:** going to look at funy do what funy does first thing I do is I'm mapping all the parameters don't even worry about the fact that this is a function right now just pretend it's you know X or something so you say funk a a is going to get mapped to the variable Z inside funy so Z is funy just mapping parameters from actual to formal then what do we do inside Funk C we print out inside Funk C and then we return Z this is the cool part inside Funk c z is Funk a so if you replace Z with funk a this here becomes return Funk a open close parenthesis look familiar we did that function call right there right so that's just another function

**[29:47]:** call so with that being another function call you're going to create another scope and you're going to pop into that one so we're one two I guess two Scopes deep we're trying to figure out where we're going so Funk A's scope is going to be up here so what does Funk a do it just prints out this and it returns none so we're going to return none to whoever called us which was Funk C so this line here becomes return none and so this line here is going to return none to whoever called it which was this line down here oops I didn't mean to cross it out so that line here is going to print none so it's if you just go step by step it shouldn't be too bad to try to map what happens with with variable names and and foral parameters and actual parameters okay that's why I highly recommend pieces

**[30:44]:** of paper and pens one last thing I want to mention about scope before we do another example so there are three sort of situations you might find yourself in the first one is probably the most typical and this is when you define a function and it's using a variable named X in this case that's also defined outside of the function and that doesn't matter because of the idea of Scopes so inside the global scope you can have variables X when you're inside a different scope you can have whatever variables variable names you want and when you're inside that scope Python's going to use those variable names so they don't interfere with each other at all so in this example I've defined a variable X is equal to one and then I increment it and that doesn't interfere with the fact that we have a variable X outside this one's a little bit trickier I Define

**[31:44]:** this uh this function G and all G does is access a variable X but notice inside G I've never actually declared or or initialized a variable X right in this F I said X is equal to 1 but in here I'm just sort of using X so this does not give you an error in fact it's okay for you to do this in python python says okay I'm in this scope but I don't have a variable named X so let me just go into the scope of whoever called me so I'm going to just temporarily hop out of this scope and see is there a variable X outside of of me and it'll find this variable X here and it's going to print out its values so that's okay this last example here is actually not allowed in Python similar to this one except that I'm trying to increment a value of x but then I'm also trying to reassign it to the same value of x the

**[32:47]:** problem with that is I never actually initialized X inside H so if I said if inside H I said X is equal to 1 and then I did X Plus equal to 1 then it would be this example here F of Y but I didn't do that I just tried to access X and then incremented increment it and then try to reassign it and that actually that's actually not allowed in Python there's a way around it using Global variables okay but it's actually frowned upon to use Global variables though Global variables are part of the readings for for this lecture and the reason why it's not a great idea to use Global variables is because Global variables sort of give you this this loophole around um Scopes so it allows you to write code that could become very messy okay so Global using Global variables you can be inside a function and then modify a

**[33:49]:** variable that's defined outside of of your function and that sort of defeats the purpose of of functions and using them and writing these coherent modules that that are separate okay that said it might it will sometimes be useful to use Global variables as you'll see in uh in a couple lectures from now Okay cool so let's go on to the last scope example okay this slide is here and notice I've bolded underlined and italicized the python tutor because I find it extremely helpful so the python tutor as I've mentioned in one of the assignments is it was actually developed by a grad student here or post grad studentstock here and it allows you to go through python paste paste the code go through it step by step like with each iteration it'll show you exactly what values each variable has what scope you're in when

**[34:50]:** Scopes get created when Scopes get destroyed variables within each scope so pretty much every single detail you need to sort of understand functions you know as we're starting to you can see we've had a couple questions and these were great questions so if you're still trying to understand what's going on I would highly suggest you take a piece of code and just run it in the python tutor and you should be able to see exactly what happens in sort of a similar way that I've drawn my my diagrams okay in all of the in all of the codes for the this particular lecture I've put links to the python tutor for each one of those exercises so you can just copy and paste those and it'll automatically populate it with that particular example so you just have to click step step step okay so having made my plug for python tutor let's go on okay

**[35:41]:** so here's an example it's going to show a couple things one is um what Happ you know print versus return and also this idea of you can Nest functions okay so just like you could have nested Loops nested conditions you can also Nest functions within functions so let's draw some diagrams just like before of the Scopes first thing we're going to do is when we have a program we're going to create the global scope and we're going to add every variable that we have and then when we reach a function call we're going to do something about that okay so the first thing in the global scope is this function definition again in my Global scope I just G as some code because I have not called it yet okay I only go inside a function when I make a function call so G contains some code so we're done with 75% of that of

**[36:40]:** that code next line is X is equal to 3 so I'm making X be a variable inside my Global scope with value three and then I have this Z is equal to G of X this is a function call when I see a function call I'm going to create a new scope so here is the scope of G with the scope of G I'm mapping variables to uh actual actual parameters to formal parameters so the first thing I'm doing is I'm saying inside G what is the value of of actual parameter x and x is going to be the value three because I've called G of X with X is equal to 3

**[37:28]:** okay next what I see inside this function so this is the inside of the function is this bit here it's another function definition again since I'm just defining the function and I'm not calling it all python sees is H is some code okay I haven't called the function H yet because I'm just defining it here with DF Okay so so that finishes this this part here the next line is x equal to x + 1 so inside the scope of G I'm incrementing X to be four then I'm printing out this line and then I've reached here H this is actually a function call and I'm calling H as soon as I make a function call I'm creating another scope so I'm temporarily going out of the scope of G and going into the scope of H so python knows that H contains some code and now I can go inside H and do whatever

**[38:33]:** I need to do so the first so H doesn't have any parameters so I don't need to populate anything like that in there X does def H does Define a variable called X which is ABC it's a string and then that's all H does what does it return none I heard murmuring but I think none was the was what you guys are saying so since there's no return statement H is going to return none okay so H returns none back to whoever called it which was this code inside G so that gets replaced with none the thing that I've H this circled red H here as soon as H returns we're going to get rid of that scope all the variables created within it and we're done with h so now we're back into G and we just finished executing this and this got replaced with none okay we're not printing it out right so

**[39:36]:** this doesn't show up anywhere it's just there so we're finished with that line and the next line is return X so X inside G is four so four gets returned back to whoever called it which was in the global scope here so this gets replaced with four so once we've returned X we've completely exited out of that uh the scope of G and we've come back to whoever called us which was Global scope and we've replaced Z is equal to G of X and that completely got replac with four the return value okay so that's sort of showing nested nested functions all right just circling back to decomposition abstraction this is the last slide you can see in in in if you look at the code um associated with today's lecture there's some other examples where you can see just how powerful it is to use functions and you can write really clean and simple code if you define your own functions and then

**[40:40]:** just use them later right and the beauty of defining your own functions that you can use multiple times later is you only have to debug the function once right I know debugging is not your favorite thing but you only have to debug this one thing once and then you can know that it's right and it works well and you can just use it multiple times all right thanks everyone
