Transcript for:
Python Basics: Conditional Statements and Loops

Hello, and welcome to Data Analysis with Python Zero to Pandas. This is a free certification course . You can register to get certified at zerotopandas.com. My name is Aakash and I will be your instructor for this course. Today we are going to continue working on the basics of Python. So let's get started. Where you should go is the course page zerotopandas.com. So today we are doing lesson two, so let's open up lesson two So less than two page, you can open up conditional statements and loops. Once again, I'm just going to click the run button to run this on binder. So we go, now we have the new notebook. I'm going to do kernel, restarting, clear output. And I am going to hide the toolbar and we're ready to get started So one of the really powerful features of programming languages is branching and branching is the ability to make decisions and execute a different set of statements based on whether the condition is true. And what does that mean? I'm going to show you with an example. So here, the simplest way to perform, to introduce a branch in your code is to use the, if statement and which is written like this. So you say if, and then you put a condition after the F and then you put in a colon. So this is to indicate that there is something below it, and now you have to, you can then put in a bunch of statements, right? And all of these statements, you have to give them a little bit of a space. So just give them four characters of space before the statement. So here, there are four characters before statement, and then we have the statement itself. then we have another statement and all of these statements, which are indented. So these four characters of space before a statement are called indentation. So all of these statements that are indented belong to the block, belong to an if block and these statements get executed only when this condition is true. Okay. So let's look at an example of that. So here I have a number. And this number has a value 34. And now I'm writing an if statement followed by a block of code. so here, what I'm saying, if a number which is 34 when, and this is a modulus operator, which attends the remainder. So the remainder when 34 is divided by two. So which will be zero because 34 is even if that remainder equals zero. So that, so this entire condition, this enteric expression returns true. So since this expression is true, then these statements get executed. So the statement we are inside and if block and the statement print the given number, which is 34 is even, and notice that we're using string formatting here. So if I execute this, you will see that these statements get executed very simple, but a very powerful idea. And you will be doing this a lot. This is the bread and butter of programming, really branching and looping. let's try another example here. Now we have 33 and then with 33, we have once again, checking if this condition is true and if this condition is true, then we are going to try and print something, but you can see here, nothing gets printed because this condition does not hold true. So that is basically if statement and what you might want though, is you might want to do one thing. If the condition is true. And you might want to do another thing if the condition is false and that is where the else statement comes into picture. so what you can do is you can have a if statement and you can have a block of code after the statement, and then you can write else and give a colon and have another block of code. So if the condition holds true, then the first set of statements is executed. And if the condition hold is false, then the second set of statements is executed. Okay. So let's check it out here. So we have a number and we say that if a number divided by two is, D leaves a remainder of zero, then we say that it is odd. Otherwise we see that it is even. So cure since 34 is even this gets printed. And then similarly since 33 is odd, the second statement that the number is odd gets printed here is another example so that you can build these conditions in any way. So it does not just have to be arithmetic. Here is another example. I have a tuple the three Musketeers, and then I have a candidate. So what we do is we check whether a candidate is in the tuple. And that makes so readable that you can just read this and understand what's going on here. So if a candidate in the three Musketeers then print that the candidate is a musketeer, otherwise sprint that the candidate is not all right, so it can build these conditions and combine them in all sorts of complex ways. and that gives you a lot of power. Now one other statement, which is you may or may not use this a lot, but there is an Elif statement that you can use. So when you want to check, not just one condition, but a series of conditions, you can use the Elif statement. So I'll just show you with an example, what it does very quickly. So what we do is we say that if today is Sunday, then we print that. We print something about Sunday ELLs. So ELs, if so elephants short for ELLs, if. So if this condition fails, then we check this condition and print something. And if that condition fields, then we check this condition. So as conditions keep failing, we keep checking the next condition. But if at any point a condition becomes true. So for instance, at today, equals redness data condition becomes true. Then we simply print out. then we simply execute the code inside that block. And then we ignore all of these. Alright. So that is the Elif statement. Check, keep checking conditions until the condition is true when the condition is true, execute the statements inside that block and then ignore the rest. Okay. And, there are a few details here about Elif and how it is different from simply using a bunch of chain, if statements. So I will leave that for you as an exercise. So here we have tried the same thing with if Elif and then we've tried the same thing with just a bunch of if statements. So I let you try that out. And finally you can use if Elif and L's together. So here I have the number 49. So what we do is we try to check if it is divisible by two, and then only printed as divisible by two, we check every little divisible by three and we print that. We check if it is divisible by five, and we print that if none of these conditions hold true, then we go into the ELLs block. So you can do a chain if Elif, elephant L statements. Okay. And then finally, what you can also do, as I've mentioned before, is within an if statement. You can take this number and, you can take, you can have a check on that number and then you can do an ad so you can combine two conditions. So you have a number divisible by a remainder with three equals zero, and a number remainder with five equals zero. And then only both these conditions are approved. You are going to go and execute this sprint statement. That the number is divisible by three and five. Okay. So that is the. that is the, if else statement. Now, one other thing is that these conditions do not necessarily have to be conditions. In fact, they can be any value and they can be any value in biotin. For instance, you could, that can be a, it can be a string. It can be a dictionary. It can be none. It can be a number. And what happens is that automatically, whenever you put in a value that is not a bullion by button automatically calls the bull function on that value. And, we've discussed this the last time in the last lecture, so you can look it up there when you call the bull function, empty values, like zero or the empty string or empty dictionary or empty list. Get converted to false and all other values get converted to true. So there are certain set of false see values, and there are risks. There are a bunch of true values. Okay. And this is pretty useful because if you want to do it a certain operation, only if a particular list is not empty, then you can simply say if my list and if my list is true, then you print something. As you print something else. So this is a very simple way to just check whether something is empty or not. and then again, a very minor thing, and you can try this out is that you can have if statements inside if statements. So here is an if block. So we are checking if a number is divisible by two or not. And then inside the blog, we have another if statement where we check, whether the number is also divisible by three or not. And then what you have to do is this, if statement itself has to be indented and then the, block inside, it will require two levels of indentation because it is indented from, an if statement, which is already indented by four spaces. Okay. So check this out, try this out. First, read this outline by line. And try to predict what will happen as you put in a number here, which path it will follow. And as you change the number, try to see if you can get all of these print statements to show up in different cases. Okay. now one small piece of advice here is avoid nesting statements if statements wherever possible. So if it's, if inside, if it's very confusing, so the. Maximum you should go is maybe one level of nesting and try to keep your code as simple to understand as possible. Okay. so that is the, if those are all the variations of the, if statement, and then there is also something called a shorthand, if expression, this is not something that we are going to cover in the lecture, but again, this is the here in the notebook. So if you're going through the notebook, you can try this out. Essentially, what is of what it offers is it offers a way to put the entire if condition statement, statement, all of that into a single line, especially when you want to calculate a new value out of the, if statement. Okay. So I will skip ahead for now. So I'm just going to save my notebook here because of this is something that you should just do from time to time, keep saving your notebooks. So you add, I just take my API key and paste it in here and that uploads the notebook to Jovian. Okay. we've gotten a lot of comments about people losing their work on binder because they left the tab open for a long time and, or left their computer for awhile. So just keep running. Jovian not commit from time to time on binder so that you do not have to deal with that problem. Okay. All right. So now we've looked at conditions. The next thing that we're going to look at is, iteration and iteration is an extension of condition or an extension of branching in a sense. So what it allows you to do is it allows you to run one statement or a set of statements multiple times. So we have something called the wild loop in biotin, which works like this. So you say while. And then you put in a condition and then as long as that condition is true. So let's say you're checking the value of a variable, whether it's even, or not, as long as that condition is true, the statements inside the while you keep executing over and over again. And on what you might normally do is that within one of these statements, you might change a variable, which might later cause the condition to become false. Okay. and that is when the while loop will end and we will continue with the execution of the program as normal. So let's take an example. you might be familiar with the concept of factorials. So what we will do is we will try to the factory of the number N is simply the product of all the numbers from one to N. So the factory of 10 is one, two, three, four, five, six, all the way up to 10. Multiply it. And so on. So we will write a while loop to calculate the factorial of the number. Okay. A factorial of the number a hundred. Okay. And so the way we're going to do this, we are going to create a variable called result. This is where this is what we'll get back, the final result, of the factorial. And then we're going to create a variable called , which is you can call it index or you can call it like a counter. so I has the value one. And then we create a while loop. So we say while I is less than or equal to a hundred. So initially since I is one, this condition is going to be true. So then these statements are going to get executed. So first we do result equals result times I, so since I is one right now, then result will continue to remain one. And then we do, I equals I plus one. So I plus one is two. So now we change the value of the variable. I do. I plus one, which is two. So now I has the value too. Now we come back here. The state, when condition is executed again, this condition is currently still true. So then we multiply the result with two. So the result becomes two and then I now becomes three. Then we check the condition again, and then we multiply result by three. So result becomes one times, two times three. And w wanting to do into three, and then we have, I get increased to four, and now you get the idea, right? We keep repeating this over and over till this condition becomes false. That is still, I becomes 101. And when I becomes 101 at that point in this condition is false. So at that point we break out of this loop. So it's called breaking out of the loop. And then we can go on executing the program, with the statements that follow it. Okay. So let's run this so you can see you done this and it took hardly an instant and it gave us the factorial of a hundred. And you can check whether this is actually the factorial. If you want to, you can look it up online. but that's basically how this code works and the real powerful thing here is that just with these four or five lines of code. We have been able to calculate the factorial of a hundred, but if you want to go from a hundred to a thousand or even a hundred thousand, all we have to do is change this. And that is what makes computers really powerful. That with a few lines of code and with their real speed of arithmetic operations, they can compute a lot of different things. very good quickly. So here we have, for instance, here we are trying to calculate though. The factorial of thousand and I've added this special command called a person time. So this person time is simply going to tell us how long it took to execute the sale. so yeah, I run the cell and I get back the, I get back thousand factorial, which is this huge number, pretty huge. And it took only a total of two milliseconds, which is like, Thousands of a second. Almost pretty much. so that's why loops are a really powerful thing in programming because they let you process a lot of data really quickly with a few lines of code. So now here are some exercises that you can try out with the Y loop. So with the Y loop here is a pattern that I've printed out. So I've just printed out this nice pattern using this asterick asterisk characters. so that takes a couple of wild loops to print these out. So try and see if you can understand what's going on here. see if you can make sense of this code and then use that to maybe create a couple more patterns. So here is one more pattern. This is the mirror image of that pattern. And then here does like a diamond pattern or a rhombus putting these two together. So try and see if you can write the code for these, especially this one. It can be a little bit tricky. So if you can figure this out, then you will really gotten a good hang of, loops and iteration and biotin. Okay. one other thing that you might want to keep keeping, keep track of is that sometimes you may make a mistake while writing your code. So here I have, I am calculating factorial, but within my viral loop, I may have forgotten to increment. I, okay. So when this happens, when you forget to increment, what happens is this condition remains true forever because I is not changing. And when you run the cell, now it's just going to keep on running continuously, forever, and you will not be able to execute any other code in the notebook. So this is called an infinite loop because the program is stuck in the loop forever. And the way to come out of this is to. Interrupt this execution, or to prevent, stop this execution. And there are a couple of ways to do that. So you can go Cornel interrupt, and that's going to interrupt the loop and then you can make the change and read on the cell and then the other option. And by the way, here is another example here. What I've done is I am incrementing. I, so again, we are calculating factorial and I am incrementing. I. but I put in the wrong condition here. So this condition again, I can keep on going to a million or 2 million, but I greater than zero will always continue to hold true. So this goes into an infinite loop as well. So the other way to stop it is if you have the toolbar open next to the run button, you have a stop or an interrupt button, so you can simply press the interrupt button and that is going to stop the execution. So those are the two ways that you can bake out of these infinite loops. And don't worry, you can always go back and fix these things. So write your loops. And then if you see that it's going into an infinite loop, just interrupt and fix it and rerun it. don't be afraid to get it right the first time. now there is a couple more things with, within viral loops. One is that you can, there is a special statement called break. so what are you gonna do with a break statement is yes, you have this condition within the Y loop and this condition can, when the condition becomes false, you will break out of it. But sometimes you may want to, depending on a certain condition, depending on what values you are iterating upon, you may want to decide that, okay, I want to stop the execution of the loop somewhere in between. And that is when you use the, if character, the, that is when you use the break statement. So for instance, here we have, I equals one result equals one, and then while I is less than equal to a hundred, we say we multiply, I V with the result. So this statement results start equals I is the same as result equals results. Start I okay. And then we have an if statement here, which checks that if, we check that if it reaches the value 42. Then we say that magic number 42 has been reached and we're going to stop the execution. And then we are going to break out of the loop. So this break gets executed and then the, we exit the loop completely. And then we execute these statements, right? So you can see here that I, at the end of the while loop has the value 42. And the result is not nearly as close to the factorial of hundred that we initially had. In fact, it will be. 42 factorial. Exactly. So that is a break statement. And then there is another statement that is the continuous statement. So the continuous statement is slightly different from break. What it does is it completely breaks out of the loop, but what the continuous statement does is the continuous statement. So here let's look at an example. So again, we have equals one result equals one, and then while I is less than 20. We increment. I, so we go from, I goes from one to two and then we check if I is even. So if I is divisible by two, the remainder of I with two, if it is zero, then we print that we are skipping I, or whatever that number is. And then we have the continuous treatment. So what the continuous statement does is that when this gets executed, anything else, all the remaining statements in the loop are skipped. So this print statement is skipped and this result, multiplication statement is skipped. Okay. so let's try it out. Let's just run this so you can see here, we started out with, I equals one and then we had, I equals two in the first loop. So we skipped two because this, if statement was true, and then we did, so there was no multiplication with two, but then we did multiply with three. Then we skipped four multiplied with five skipped, six multiplied with seven and so on. And the result that we get back ultimately is the product of all the odd numbers from one to 20. Okay. So that's the continuous statement. So break and continue are well, they're not very often used, but they are quite useful sometimes when you are stuck in a tricky loop where you want to somehow, have something come out of the loop based on a certain condition. Okay. So that's, so those are loops and I'm just going to run Jovi, not commit once again, just to save my work. So those are wild loops. another important kind of loop. In fact, something that you will probably be using the most often is the for loop. Now just as Y loop is used to iterate while a condition is true, the four loop is used to iterate or loop over a sequence. for example, if you want to perform an operation for every element of a list or a two-page or a dictionary, or every character in a string that is when you use a four loop and they have a very nice, simple, intuitive syntax. So what we say is for value in sequence. for value in sequence. So we have a sequence and then we take using the in operator a V take one by one, each value from the sequence. once we put it into this false statement and then we can execute the, a bunch of statements, repeatedly, a bunch of statements for each value from that sequence. Okay. And it'll become clear with an example. So here we have a list and the list has, Monday, Tuesday, Wednesday, Thursday, Friday. So it has these elements. These are all strings and we say four day in days. So four day in day. So what happens is that every time this for every element Monday gets put into the variable day, and then you can print day. Then Tuesday gets put into the variable day and then the statement gets executed. Then Wednesday gets put into the variable day and then the statement Caltech, it gets executed and so on. Okay. And you can see here, as you might expect, Monday, Tuesday, Wednesday, Thursday, Friday gets printed and here are a couple more ways you can try this out so we can actually loop over a string and we can get back characters from the string. So for every character in the string, Reprint out the character. So here Monday becomes M O N D a Y. We can loop over it to pill or a list. this is more of a list than a pill. So here we are going to loop over the list, Apple banana guava, and then we're going to print it out saying here's a fruit. So here's a fruit, Apple, banana, and guava, or we can do poet a dictionary as well, which is again, something that we will do a lot over the course of. The next few lectures. So here we have a dictionary and then we are going to use the name, John DOE, sex male, age 32, married. And then when we loop over a dictionary, what we get back is just the keys. We do not get back actual values from the dictionary. So if you want to access the value. So here's what we do, right? So for key in person, and then we're going to print out the key. So the key is going to have the values, name, sex age, et cetera. And then if you want to get the actual value stored against that key, then you simply pass the key into the dictionary. Using the indexing operation, right? So the person key of keys name, we'll give you the name and so on. So let's run this. And so you can see here, the key is name and the value is John DOE. When the key is sex, the value is mil. The key is age. The value is 32. The key is married. The value is true and that's all it is. if you do want to iterate over actual values, then you can just call the dot values muttered. On a dictionary. So personal values will now give you a list of values. And now you see, we have just the values. What if you want to get back both keys and values, then there is also something called a dot items and then dot items is going to give you both the key and the value. All right. So that's our four loop with a four loop. We can iterate over a bunch of different containers, but sometimes you might want to iterate over simply a bunch of numbers, right? You Mo you might want to run something you might want to run a loop from, let's say numbers from zero to a hundred, and then perform certain operations using those numbers. And that is where you can use. The range operator, sorry, the range function. So here are a few examples. So if you just say for I in reign seven, so when you say it in seven or any range, and that creates a sequence of numbers from zero to N minus one. So rain seven creates a sequence of numbers zero to six, and you can see that here, if I print it out, that's going to create the, range of numbers from zero to six. You can also specify a start index and an end index. So what you can do is you can say range of three to 10. So what that does is that starts with three and then goes all the way up to 10, but not including 10. So that becomes three, four, five, six, seven, eight, and nine. So you can see three to nine, get printed here, and finally, you can also give a step. So here we start with three and we go all the way. Not. Equal to, or greater than 14. So we can go all the way up to 13. but we take increments of four, so we have three and then we have seven and then we have 11 and then 11 plus four becomes 15, which is greater than or equal to our end index. So that is not printed, right? So this is pretty useful. Range is pretty useful when you also need access to, let's say you want to go over a list, but you also want to know within the loop, which element in the list you're accessing, right? The index of the element. So that is when a range is useful. That let's say if you're going over to, if you're going over a list here, you have the list of days. what you can do is you can create a range with the length of the list. And then you have the index, I, that goes from zero to the length of the list minus one. So zero one, two, three, four is, are going to be the indexes. So you can then print that the value at a position, zero is Monday and the value at the position. One is Tuesday because we are formatting the string and we are putting in I the value of the index. And then we are getting the element with. With that index out of the list. All right. So that is the range function and similar to why loops for loops also support, break and continue statements. So anywhere within a four loop, if you feel like, okay, you should probably end this loop right now because maybe you'll find it the loop. And similarly, here is the continuous statement. So here you can see that beyond Wednesday. We do not process Thursday and Friday. But in the same way, if we were printing things out and we were simply doing a continue, then what happens is that when we reach Wednesday, this statement becomes true. So we print, I don't work on Wednesdays and then we say, continue. So this print statement below gets ignored. All right. So here are with continuous sort of break. We say today's Monday, today's Tuesday. I don't work on Wednesday, but we still process Thursday and Friday. So those are the break and continue statements. And finally, this is not very common, but sometimes you may want to just create an empty loop, nothing inside a loop. So you just say four day in weekdays, and then you say POS, So if you say past nothing happens, you simply go over all the elements, but nothing really happens. Now that said about live loops that we'll cover right now, you can nest for and Y loops inside each other. So I leave that as an exercise for you to try out. You can nest for loops inside wild loops. You can have if conditions inside for loops inside wild loops and so on. But again, even just as with the conditions, if you nest too many loops, it can become difficult to read and understand. So you may not want to do more than two levels of nesting within a loop. Okay. That's all the discussion that we have about variables, data types and, branching and loops. And then I'm going to go back to lesson two. And now we're going to try, now we're going to look at a very interesting topic or something that is at the very core of programming, and that is the idea of functions and scope. Okay. So open up the notebook. Let me just click run on binder. Wait for that to get started all right, so let's just go full screen and let us hide the toolbar. So I'm just going to do kernel, restart and clear output. Okay. So we have already seen some functions, right? We've seen the print function. We've seen the Len function. We've seen the data types related functions which can convert data types from one type to another. And then we've seen methods as well. But just to recap, a function is basically a reusable set of instructions. That is, there is some logic which you think can be used again and again, on different data or needs to be, your do not want to write the same set of code each time you want to do that, perform that operation so you can work it into a function and a function takes one or more inputs. Perform certain operations on those inputs and then often returns an output as well. Okay. And biotin provides many built-in functions like Brent land and so on, but you can also define your own functions. So this is the print function, pretty straightforward. We've seen this, but here are the inputs today is, and then today, that is an input as well, which becomes Saturday. And that the print function simply performs an operation, which is displaying the input on the screen. It does not return anything. Okay. Biotin allows us to define our own functions as well. So what we can do is we can define a function let's say called C Hulu, and now the CLO function can print. Hello there. And the sale look, functionable, print. How are you? So it's a pretty straightforward function, the way to do it as deaf space function name. And then you have these parent theses or these, round brackets inside it. You can put some inputs, but we're not doing that just yet. And don't forget this colon character. And then the body of the function needs to be indented by four spaces, just like the body of a four loop or just like the rodeo for a while loop or an if statement. Okay. So that's a function has been defined, but when you define a function, the statements inside the body are not actually executed, then that's where you do not see anything printed here. So once a function is defined, you need to invoke it or you need to call it. So that's the same thing you will hear in vocation. You would hear function call, you will hear function execution. It all means the same thing. So the way to invoke a function is to call the function name. So just type the function name and then pass these brackets. So an open bracket and close bracket that is used to invoke the function and you can provide any inputs here as well, but our function does not take any inputs, so we're not going to do that. And then we just run, say, hello, and that is going to print out. Hello there. And how are you? Let's try it again. So if I run it again, it once again, Prince, hello there. And how are you? And that is really the key benefit that now I only had to write it once and now I can use it with a single line. I do not need to type out the code again. Okay. but it just functions. We should do not take any inputs are not very interesting. So functions can also accept one or more values as inputs, and sometimes you will see them referred to as arguments or parameters. And there are some technical differences, but ultimately. These words are used quite interchangeably. And these, so we'll go with the word arguments because that's the most common thing that you see used. So arguments to a function, help us write flexible functions, which can perform the same operation, but on different values. Okay. so for instance, we will create a very simple function and then we'll see this function that is already there. So here we say. We have a function say hello, and we will let it accept a name. And then we will print. Hello. And we will do a string formatting and we will pass in the name. Okay. So if we just say hello to John that says, hello, John, and see a lot too. Jean and that says, hello, Jean. so just taking that idea forward here is an example of a function it's called filter. Even what it takes is that it takes a list of numbers, a number list as an input, and then it does certain things and then it returns an output. Okay. So there's an input going on here and then there's some operations being performed here. And then there is a return statement. so I'll tell you what this operation, what it does and I'll not go over the code exactly. But what it does is it takes the list of numbers and it only keeps the numbers. It only retains the numbers that are even all right. So the result list will contain simply the numbers out of list, which are divisible by two and the way it does it is it iterate it looks over the number list. And it checks whether that number is divisible by two or not. And if the number is divisible, it appends it to result list. And then it turns the result list. Okay. So let's try it out. So here, and by the way, the return of function returns to return a value. You simply say return and then pass the variable or the value that you want to return. And what you can do now is we can invoke, filter even with a list of values. And then we can take this. Output or filter even, and put it, so use an assignment operator to assign the output of filter even to the variable even list. All right. So we have the way we have one, two, three, four, five, six, seven, and then we have the even list. So you can check that deli even list only contains two, four, and six. Okay. And now you can take the same filter, even a function, and then you can run it with a different area. Let's say one, three, five, seven, nine. And this time when we done it, we get back the empty area or the empty list and sorry. Okay. So those are functions. And then now we have functions through the return values. So the next thing we want to look at is how to write great functions in Biten because as a programmer you will be, and you should be spending most of your time writing. And using functions. the more functions you write, the better you get at programming, because you then learn to structure what you need to do into small functions that you can reuse in different ways. Okay. And we are going to explore how to write a great function, and using the many features that Python offers. And we will do this by solving a problem. It's so let's see. So here is the problem that we'll try and solve. So Radha is planning to buy a house that costs 1.2, $6 million. So $1, 1 million, $260,000. And when you buy a house that's so expensive, you have to probably get alone. So she has to, she's considering two options to finance a purchase. So she has one option, which is to make an immediate down payment of 300,000. So she just pays 300,000 right now, and then take a loan an eight year loan with an interest rate of 10%. So alone has her duration. The duration is eight years. You have to repeat an eight years and there is a certain interest that you pay. So there's a 10% per annum interest rates. So I should probably just put in per annum here. Okay. So that is a 10% per annum interest rate. And then there is a 10 year loan, which has an interest rate of 8% per annum. Okay. So she can either take out an eight year loan for just the remaining amount. If she pays 300,000 right now, or she can take out a 10 year loan with an interest rate of 8% for the entire amount. Now both of these loans have to be paid back in equal monthly installments, Also known as EMS. So now what we want to figure out is which of these two loans is going to have a lower, equal monthly installment. Okay. And this is the problem we solve. And then we'll build this function step by step. So we'll also see how to build a good function and we'll use certain features of Python to make it very flexible and powerful. Okay. So the simplest thing that we can do, and since we have to come, since we have to compare in mice, we need to calculate these EMI's are monthly installments for both of these loans. So it'd be helpful to define a function so that we do not have to type out the same logic for each of these loans. All right. So we're going to define a function called a loan EMI. And to start with, we are going to simplify it a lot. We're just going to say that. Okay. You just give us the amount and we'll assume that there is no down payment. there is no interest. And the loan has to be paid back in exactly one year in monthly installments. Okay. So we simply take the amount and then we divided by 12 and, that gives us the EMI. And then we print out the EMI. Okay. Using the print statement. So Lewin to our loaning, my function just takes one input. So here we call with a 1.2, 6 million as the input. So you can write it like this one to six, 1 million to 60,000, or you can also just say 1.26 , which makes us 1.26 multiplied by 10 to the power of six. So that is 1.2, 6 million. Okay. So if you take out the entire amount you want to repay in 12 months, then this is the amount that you need to pay per month. Pretty simple, straightforward. That's fine. So now let's add a second argument. So let's, apart from the amount, let us also include the duration of the loan in months. So in, after what time are you going to completely repay the loan? So you have the amount and then you have the duration in months. So we put in the monthly, we put in the duration here and all we need to do is divide the amount by the duration. And once again, we're just going to return the EMI. Okay. So we've just extended our functional little bit and step by step. We're going to just make it better. Now, one thing I want to note here before we actually use this function is that you will see that I've actually created a variable called EMI here. No. Where does this variable live? Because if you're trying to access this variable, let's say I try to access EMI. That is, it says the EMI function, my variables not defined. And it's not if I call the function, it will become defined. if I let's say, if I just call with a 1.2, six e-cigs and with a duration of 10 years. So that is 10 times 12. So we need the duration in months. So the function has been executed, but even now the EMI variable is not accessible, not only the EMI variable, but even the amount and nutrition. Okay. So even if you try to access these. They are not, accessible. And that is because these are all local variables within the function, right? So a function, when you define a function within the function, there is a scope and all these variables, which are used inside the function are only available within the function and they are called local variables. So scope is basically the rules that define where a certain visible, where a certain variable is visible. So if you have a funk, if you have a variable that was designed, defined outside in a separate code cell, That is a global variable. You can access it anywhere in your code. And then if you have a variable that is defined within a function, that is a local variable. Okay. And that's a very useful thing to have, because now you can define, let's say five, 10, 15, 2000 functions in each of these functions, you can use the same variable names without worrying about what you do with a variable in one function inside of function, effecting the value inside another function. So each of these will get initialized from scratch inside the function. So that's just a little note on scope. Okay. So now we can compare a eight year loan with a 10 year loan. For the eight year loan, we pass in eight into 12, those many months. And for the 10 year loan, we pass in one, 120 months. We still do are not considering the down payment. So you can see that the EMI, obviously for the ten-year loan will be smaller than that for the eight year loan, as you might expect. Okay. I know this is great. We can see visually that these values are different, but it would be nice to compare them as numbers and maybe we want to calculate the difference and so on. And that is where we can actually use a return value. let's modify our loan EMI function now, and this time, what we are going to do is we're going to return the value of the EMI. So we're going to say, amount EMA is amount divided by duration, and then return the EMR as a value as an output. Now when we call Looney ma on eight years, we can actually take the output and then put it into an EMI, one variable, and then we can then go for EMI and take the value of the ten-year loan and put it into EMI too. It's now we get an EMI one and EMI too, and we can now take a difference of these two and we can check. Okay. Okay. There's a difference of $2,000 between the two EMS. Again, right now, we are not considering down-payment or interest. but it's a good, it's a good thing to see how things are evolving. Okay. So next up, let us add the down payment. the immediate down-payment the amount that you're going to pay right now that needs to be deducted. And the rest of the amount is what you need to take the loan for now, since the first loan has a down payment, but the second one does not, what we can do is we can make this an optional argument. with a default value of zero. So now we still have the amount, we have the duration, but we have the down payment and the down payment has a value of zero. So now the loan amount becomes amount minus down-payment and now the EMA becomes the loan amount divided by the duration. And then we return the EMI. So here for the, when we have an optional argument, we can invoke it just as a normal argument. So here we say, be passing the loan amount. We pass in the duration, and then we pass in the down payment. That's the first loan, the eight year loan with a down payment of 300,000. And now we get back a $10,000. We get back $10,000 EMI. But on the other hand here, what we have is a view just passed in the loan amount and we just passed in the amount and duration. And we've not passed in a third argument. So when we do not pass it in by 10 takes and converts this, biter simply uses a default value. Down-payment zero. So the loan amount simply is the whole amount. And hence you get back the EMA for the second loan. Okay. So optional arguments, very useful to have makes it functions very flexible and easy to use. Okay. So next, now let's add the interest into the calculation. And this is the part you may have been wondering. how are we going to calculate interest? How are we going to introduce that? And we're just going to use a formula here, and it's not a very difficult formula to derive if a little bit of math, like arithmetic, progressions, and such. but I'm not going to go into the derivation of this formula. I have linked to a video if you're really interested in understanding how it works. But the idea here is to get the equal monthly installment. We take the loan amount, which is also called the principal, and then we multiply it with this expression. So we multiply it with the rate and this rate needs to be the rate of interest per month. So not that the reach that we are given our input annum, we multiply it with one plus R so that one, plus the rate. Raise to the number of months, right? The number of periods that we want to talk about. And then we divide the whole thing by one plus R to the power N minus one. Okay. again, it's just a mathematical formula and we simply need to convert that into Python code. So let's do that. So now once again, we are going to introduce, and we have the amount. We have the duration. We have the rate and then we have the down payment. Now, one thing to notice here is that all the required arguments in the function, the form, the arguments that have to be specified have to come before the optional arguments, because what happens is otherwise, if you invoke loading, am I with three arguments by 10 may get confused. Whether you're trying to refer to the down payment or you're trying to refer to the rate. If down payment is before rate. So remember to keep all of your optional arguments at the end of the function definition. So once again, we take the loan amount that is the amount minus the down payment. Then we have the EMI, which is the loan amount multiplied by the rate multiplied by one plus rate raised to the power of duration. And that's why we took the duration in months. And remember the rate has to be monthly as well. And then we divide the whole thing by one plus rate, raised up duration minus one. All right. So that's our loan in my function and we are getting there. So now we have the down payment. Now we have the EMI and now we have the rate of interest. And now we have, the. Duration included as well. It's not, when we talk about the eight year loan we pass in, the duration is eight multiplied by 12. And then we pass in, the rate so that it was 10% per annum, which is 0.1 and 0.1. So the monthly rate becomes 0.1 divided by 12. So that's what we've put in here. And this was the down payment and that gives us back what the email looks like around one, four, five, six, $7, $14,000 per month. And then similarly for the second option, we simply put in the amount and then the duration and the rate, no down payment. And then we get back the EMI value. Okay. So now this is good. And now we have already answered the question. So we have, we can see that option one has the lower EMI, so that's good. Rather can now decide what to do, but. If you look at this function call, it's not looking very pretty. It's not easy to tell what are all these numbers that you're putting in here. In fact, it would be really easy to make a mistake here. I could very easily, if I do not remember things correctly, I could just put in this here and then that would still give me a result, but that would be a completely false result, right? This is completely wrong. So the way to avoid that, Is to use something called named arguments. Okay. So while in working a function with many arguments, it can make, it can get confusing and there can be human errors. So what you can do is you can specify the name of the argument before the actual value that you pass in. So you can say lonely, am I? And then I have written out each argument on a separate line, and you can do that. You can split the function in vocation, into separate lines, but you don't have to, you can write it all on the same line as well as I've done for the second case. But the key idea here is you can type the name of the argument, then putting an equal to, and then put the value in. So this can be a value of this can be a variable. This can be an expression like here. This is an expression. Eight multiplied by 12. here is the rate. And then here is the down payment. Okay, so that looks much nicer. Now we, and by the way, when you do that, you can actually change the order of arguments as well, because you're specifying the name. So you can actually put duration before you can put duration before the amount and so on. so that's the EMI one. So that's about one. You get the same result, no change, even though I changed the order of the arguments, then we have. Then we have . This is for the loan without the down payment, the ten-year loan 8% rate of interest. And once again, we get back the same result. Okay. So this is fine. This is good. But if you see this, I don't like this whole, pen characters of 10 digits after the decimal, because normally you're going to, normally you're going to pay back whole dollars. So what we might want to do is we might want to round this up to full dollars. And just a second. Yep. So we might want to round this up to $40 and, what are you gonna do is you can maybe write a function. You can write a function called. A up. Okay. And that takes a number X let's say, and then try to figure out what you can do here. So try to figure out what you can do here, round it up and return the result. And you can use this function inside the loony. My function. So functions within functions, using functions within functions is a very powerful technique. you can try this out and it'll be a good exercise, but since this is such a common thing, rounding numbers up and down 10 provides a built-in function for it, except that this built-in function is part of the Python standard library. So because there are a lot of Putin is a general purpose language that is applied to many different, use cases in scientific computing and data analysis in software development. So it's not, it doesn't make sense to just put all these functions into the global namespace, because that is going to just put in tens of thousands of function names into our global namespace. And every time you try to declare a variable, it might collide with a function or your known function names might collide with functions. So what Python does is it puts them into modules, right? So modules are nothing but files containing Python code so they can contain variables. So these are files with a.by extension, and then they can contain variables, functions, glasses. And what they do is they give you a way of organizing large fights and projects into files and folders. And the key benefit that modules offer is a namespaces. That is when you. When you want to use something from a module and we'll see an example very quickly, you need to first import the module. And then all the methods, all the functions, everything inside the module will have to be accessed using the name of the module. So that makes sure that your global namespace that you're working with do not get a, does not get affected. And that allows people like if you have 20 people or a hundred people working on a project, Everybody can write their own modules and they can use the same variable names. They can use the same function names, and that will not cause problems when you want to use those modules together. Okay. So here is, and by the way, you can write your own modules, but we are going to use some built-in modules from the Python standard library. Okay. So I'm going to import the math module that contains a lot of math related operations. And inside the MATLAB module, there is a function called seal, a C E I L a, which stands for ceiling, which basically takes a number and then around it up. so if I want to know what the ceiling function does, I can simply call help on ceiling. And here, it says the ceiling of X as an integral is swatted returns. It takes a single value X and it does a smallest integer that is greater than equal to X. So that's exactly what we want. It's not to invoke this function. We say mat not seal. And that rounds up 1.2 to two. Okay. So that's great. So now let's update our loan EMI function to it is the same function as before amount duration rate down payment. Get the loan amount minus down-payment calculate the EMI using the formula and then call Matt Dortch seal on EMA and the store that result back into EMI. So this is just going to do that rounding up. And now if we calculate the EMR, you can see that, one, four, five, six, eight is the EMI for the first option and one four one five two eight eight for the second option. So we can compare these EMI's or equal monthly installments now, and then we can print a nice message. Vitra duck in view. So you can imagine you're building the system where people can put in a bunch of loan options and then they get back. Whichever is the best or whichever has the lowest EMI or whatever it is maximum optimize for. And yeah. and that's it. So that's, that's one way of just using functions and we've built this function step by step and we've made it better over time to answer this problem. Okay. but apart from just answering this problem, what we have achieved here is actually we've created a fairly generic function that can be used to solve many other similar problems. And now we do not have to think of that entire logic. Like we do not need to remember the formula. We do not need to. figured out how to round things up and so on. So let's try a couple more problems and let's see how easily we can solve them using these functions. So here, Sean is currently paying back a home loan for a house he bought a few years ago. So Shawn has a loan of $800,000. The loan has a duration. The duration was a six year duration. And the loan has a down payment of a 25% of the cost. So which is 200,000, right? So there's a down payment of 200,000 on an $800,000 loan, sorry, on an $800,000 house. So the rest of the amount is on a six year loan with an interest rate of 7% per annum. Okay. Now that's one loan that Shawn has another option. Another option is, another thing that Sean is doing is Sean is now buying a car. What? $60,000 annually. It is going to finance this car, using a one-year loan with an interest rate of 12% per annum. Okay. And both loans are to be paid back in EMS. So what is the total monthly payment? That's one has to meet, okay. Looks a little, it's a bit complicated, but if we break it down, there are just two loans going on here. So here is the first loan. Cost of house is, such and such. the six months is sorry. Six years is our duration. 7% is the rate of interest. And 25% of 800,000 is the down payment. We simply put it into the loan EMI function and we get back the EMI of the house as 10,000, $230. Here is the second loan. So we have a $60,000 loan. The duration of the loan is 12 months. So one times 12 and the rate of the loan is 12% per annum. So we need to divide it by 12 to get the monthly rate. And then we put it into loan EMI, and that's it that, we get back the EMI for the car is $5,000 per month. And now we can display the totally mine that Sean makes a total monthly payment of the EMI of the house. Plus the EMI of the car. Towards loan repayments. Okay. So yeah, that's great. We've just sold. We've sold another problem using just these one, two, three, four, five. This is technically just one line of code split across multiple lines. So five lines of code for the first loan and four or five lines of code for the second loan. And the problem is solved. Okay. Let's try one more. And this one is a little more interesting. So here, what we have is if you borrow a hundred thousand dollars, And you are on a 10 year loan and you're using, you have a rate of interest of 9% per annum. So what is the total amount that you end up paying as the interest? So over and above the principal, the a hundred thousand dollars, what is the additional amount that you end up paying? So there are a couple, there's a one simple way to do this. and what we can do is we can assume that there are two loans. One with interest and one without interest. Okay. So here's the loan with interest. It has the value amount of a hundred thousand. It has a duration of 10 years, and it has a rate of interest 9% per annum. So that gives us one, two, six, seven is the EMI with interest. Okay. Now let's suppose that there was no interest on this. So what we can do is we can simply get the EMI for the loan without interest, and then. If you subtract the two EMS, we get to know how much interest we are paying per month. And then we simply take that over the entire duration. So that gives us the total interest rates. That's one way of solving it. There are other ways too. So let's put in the amount a hundred thousand, let's put in the duration and let us put in the rate of interest Zito. Oops. But something seems to have gone wrong here. And let's see what went wrong. Now, this will happen to you a lot before, before you get better. And even after 12 years of doing Python, I still get exceptions all the time. So don't worry if something goes wrong, just, when you want to start is look at the last line. So it seems like this is a zero division error. So what happens is whenever you try something that causes something to break. while the code is executing Putin throws an exception by throws. What it means is wherever the error occurred, it is going to stop the execution of the program there. And then it is going to just print out this error message for you. So it seems like there was a zero division error. we were trying to divide a divide by zero and float division is simply the normal single division. So we are trying to divide by zero, wherever we trying to divide by zero. That is very now go up. And see that. Okay. Within the loan EMI function, if you check the third line, this is where this arrow points. So in this formula, it seems like we're dividing by zero. And now you can probably guess because the rate is zero one plus rate becomes zero. And because one plus rate becomes zero one plus, sorry, one plus eight becomes one. So one plus rate to the power of duration becomes one and one minus one becomes zero. So this entire denominator is now zero. And that's a problem because now. Dividing by zero, is not defined. And so the EMI, so the low Nehemiah returns an error, and that is why the EMI without interest, the code execution stops at this point and nothing gets printed. Okay. what do we do? So when an exception is thrown, when the, when an exception is thrown by patent, you have a chance to actually handle that exception and an exception, the way to handle it is using a tri statement. Okay. So here's a small example. So what you do is you say, try whenever you're writing some code, which you think might cause certain errors. So you say, try and then here, I'm going to print a statement in computing, the result. And, but then I'm going to divide five by zero bad idea. it's going to break here and then I'm going to just say computation was completed successfully. So now, since I know that this might break when this maybe zero came in as a function argument or something like in the previous function. So when I know that this is going to break, I can put in an except statement and put in that type of error that I might expect. So the except statement and then the type of error is a zero division error. So here, what it is saying that if you get a zero division edit while executing this code, then do this. So what we do is we print that we fail to compute the result because you were trying to divide by zero and then we set the result to none. And then we simply print the result out. Okay. So you can see here, it says now computing, the result, it tries to compute the result and it blows up. Now the print statement, this one does not get executed because we've broken out of the execution, but they accept, handles the error and then these two statements get executed. So we say that you fail to compute the result and result has the value. None. this, on the other hand, if I were doing five divided by two, so now this runs normally, so we never come into this error case and we simply print out that the computation was completed successfully and the result has the value 2.5. Okay. And. This is what you can do. You can actually have multiple accepts statements. If you know that there can be multiple types of errors or exceptions that can be thrown. And Python has a lot of different exceptions. So you can actually check out, I've appointed to a link here. You can learn about more exceptions in Python, but what we want to do is we want to just take the loan EMI and add the tri except inside it. Okay. So what we want to do is we want to try, we want to try to calculate the EMI for the loan, using the formula that we had. But if that returns an error, especially if it leads to a zero division error, then we can say that the loan, if the zero division error will occur only when the rate is zero and when the latest zero, you can simply divide the loan amount by the duration. So then we simply divide the loan amount by the duration, and that handles the error for us. Then we, again, around it up, and then we return it. Okay, so that's great. so now we can use this updated loaning in my function. Once again, the question was you borrowed a hundred thousand dollars using a 10 year loan with a rate of interest of 9%. What is the total amount you end up paying? So we calculate the EMI with interest, and then we calculate the EMI without interest. And this time it works even with the rate of zero, and then we can see that, okay. There's a difference, a significant difference with, and without the EMI. So we do the EMI with interest minus the EMI without interest. And then we multiply it with the duration of the loan, which is about 10 years, right? So 10 times 12, that those many months. So that gives us the total interest at a speed. And now we can display that the total interest paid is five 50, 1,960. Okay. And that's a good thing to know whenever you're taking a loan. What is the total interest you're going to end up paying. And are you okay with that versus just paying it? All right. Last thing. Now we can also add some documentation within our function using what is called a docstring. So this is what we saw the health method that we used with. The seal MassDOT seal. Okay. Now, how do you, if you want to add your own, if you want to add explanations within your own functions and you should do that, the way to do that is to include a string as the first statement within a function. So you, so here I'm using a multiline string. So here, I'm going to say that it calculates the equal monthly installment for a loan. So that is a description of the function. And by the way, you can just write that. And that should be good enough to put a lot of things. So you do not need this necessarily, but anyway, I'm going to, I'm going to use this too. So I put in one line about the function. Then I am just giving a space just to make it a little clearer. And then I'm saying, I'm going to just describe the arguments as well. That the amount is the total amount to be spent. So here I might want to specify that do not like this should be the loan amount plus down payment that you're putting in, then their duration is simply the duration of the loan, but in months. So that's an important detail to give. And then the rate is the rate of interest, but it's monthly. And then finally the down payment is an optional argument. It is an optional, initial payment deducted from the overall amount. Okay. So this is how you, this is how your document Estring, sorry. Document of function. That is explain what it does for the people who are going to use this function. And the rest of the body of the function is the same, right? So the rest of the things just go in the body. Now, when you have the document, when you have the documentation, you can simply call the help function, and you can see that the same documentation gets printed. So this is very useful. It will be useful for you. It will be useful for others using your function. It will be useful for people reading your notebook as well. So if I never possible write documentation for your functions, Okay. And now we can just save and upload our notebook. So again, since this is running on binder, I don't want to lose my work. So I just grabbed my API key here and put it in. And as you keep committing notebooks to your profile, they will get added up here. So you can see here, I have a bunch of these notebooks. and you can always come back and run any of these. And then if you commit again, then they will get updated. So each of these notebooks, you can see how many versions they have and so on. And you can also share these notebook links online with your friends. If you want to just give a quick tutorial or answer a question. Specifically, even on the forum. If you want to answer a question and you can quickly create a notebook to do it. So you just do new notebook, create a new notebook, run it on binder, type out the solution, and then committed back. So once you get a notebook on Jovian, you can commit it back and then you can simply share the result on the forum. Another thing to do is if you're getting stuck at some point. Then just commit your notebook and take the notebook link and post that on the forum saying that this is what I've tried, and this is how I failed. Unless you describe what you have tried. It's very hard for people to help you out. generic questions like I'm not able to solve this problem is not very helpful because people will not be able to help you. So the best way to get help is to offer as much description about what you've tried and the best way to do that is to share the actual notebook that you have been using. Maybe just. The piece of code that you are, working with. Okay. So that's about functions and there's a lot more to function. So just a quick review of what we've covered. And I'll talk about an exercise for you. So we've talked about creating and using functions, and we've talked about creating functions with one or more arguments, and we've talked about local variables in scope and returning values using return using default arguments, using named arguments while invoking a function. Importing modules and using the library functions, reusing and improving functions to handle a new use cases, to what we saw as we kept improving the learning in my function over time. And this is something that you should do a lot, keep improving your functions and we handle exceptions using try, accept. And then finally we documented functions using bulk strings. So that's a lot of ground that we've covered in just 45 minutes. So I hope you've been able to follow. And if not, you have this notebook, so experiment with the notebook. So what you should be doing now after the lecture, you should be going file new notebook by ten three, take this notebook Putin, put it on one half of the screen, take this other notebook, the existing notebook and put it on the other half of the screen. Okay. And now what you should be doing is you should be actually typing out all of these things by yourself. So for instance, the lonelier in my function, instead of just looking at the function and trying to understand it, you should be defining it should be saying Def lone EMI. And then I'm just going to take the amount right now and return amount divided by 12, and then just try it out, just try to bake things, just say, okay, what happens if I pass in loaning? Am I, I take a loan of a hundred dollars. Okay. That seems to be the. EMI. Now here, you might get certain ideas. What if I pass into argument? What if I call it without any arguments? If you call it without any arguments that says, oops, it's going to tell you that the lonely, my ex has one positional argument amount, which you have not passed. You can try calling it with multiple arguments. That's going to give you, So all of these questions that you might have, the more curious you are, the more you break things, the more you'll learn. And the best way to do that is to just type out the code yourself. Because as you're typing, you will wonder what can I change here? What can I break here? And. The more you explore, the more you learn about Putin, the better programmer you will become. Okay. All right. So now we have, an exercise for you. This is not an assignment or anything. This is just for you to understand. so here you're planning Alicia trip, and you need to decide which city do you want to visit? So you've shortlisted four cities and you've identified what is the return flight cost and what is the hotel cost per day? And what is the weekly car rental? cars have to be rented for full weeks. So even if you want to use a car for two days, you still have to pay for the week and hotels are rented per day or per night. And then you have the return flight, which is just a one-time cost. Okay. So using this data, and this is a real life example of, again, some analysis that you might have to do in real life. So using this data, if you're planning a one week long trip, which city should you visit to spend the least amount of money? Okay. So that's one question you can answer. And how does that answer change? If you change the duration of the trip? From one week to four days or maybe 10 days or two weeks. So it's a good thing to explore all these things. if your total budget is a thousand dollars, then which city should you visit to maximize the duration of your trip? Or maybe you actually do not have a lot of time, but you'd have a good budget. So which city should you visit if you want to minimize the duration of your trip? So these things are something that you can figure it out and then you can change the budget, try $600, try $2,000, try $1,500. And all of these things. And to do this, it will be very useful for you to define a function like cost of drip, which will take in all the relevant inputs, like the flight cost, hotel rate, car rental rate, and duration, and it will, calculate the duration of the trip. Alright. And calculate the cost of the trip. and then you can use that to answer all of these questions or any other questions that you may have. So do try this out. This is going to be a good exercise on functions. And what we will do next time is we will, then we will continue working on functions, but we will also see how to work with fire. So we will process some files and then we bid perform certain data analysis and certain operations on from data read from these files. What should you do next? Try out the notebooks yourself. as he said, open up side by side and then type out the code, start working on the assignment. So assignment one once again, just to repeat you, go on the lecture pays zero two pandas.com. Click open here on assignment one and run the notebook. Make some changes committed back to Jovian take the German Lincoln submitted here So we'll take your last submission and evaluate it. And based on that, we'll give you a pass or fail grade, and that will be done. Another very important thing to do really learn things well is to ask and answer questions on the forum. so I would suggest make it a point to answer questions on the lecture forum thread, which you can access from here. So here's a discussion forum thread, or in general, from the course page, you can just find the course community discussion forum. So you can click through to that link as well. And you can find all the discussions that are happening. Lecture two assignment, one lecture, one, and so on. And just try and at least ask one question per week and answer maybe two or three questions per week. The more you answered the better your understanding becomes as well. so please do that. A lot of people are helping each other. So I just want to give a shout out to everybody who has been helping out Talk to people on the forum. Ask questions, try your own ideas. Try to break the code. The more time you spend on this, the better you will get at it. So I will see you on the forums.