Posted on 1 Comment

Learn Matlab Episode #5: Linear Algebra

Click here to subscribe for more videos like this!

Linear Algebra in MATLAB

So in this matlab tutorial we’re going to talk about some basic linear algebra in matlab. The first thing I want to talk about is how to solve linear equations. So in general these are in the form of A(X) + B where A is a matrix, X is a vector of the variables you want to solve for, and B is a vector of constants. So if you remember from linear algebra a system of linear equations is when you have more than one variable and the same number of linear equations. So, in this example I’m looking at right here the variables are X, Y, and Z and because there are three of them I have three different equations. So one way of writing the problem is just writing the equations out explicitly like this, or you can write it out in matrix form. So, in this example A = [3 2 -1; 2 -2 4; -1 0.5 -1]; OK, so that’s A, b = [1 -2 -2]; ok. So, when you’re working with equations like this you might be tempted to do just simple algebra, so you could say x = inv(a)*b because mathematically that works. So, I can do that oh and right I have to make b a column matrix, so a*b. Sorry, I used the wrong b so inv(A)*b so I get 1 -2 -2 which is the answer given on Wikipedia. So sometimes when you try to do something like this matlab will give you a warning this is a very inefficient way of calculating this answer. It’s matlab already contains algorithms to solve this problem. So if you remember from before when we were talking about operations we were talking about the division operations and how there’s a forward slash division and a backslash division. So, this is the use case where you want to use the backslash division. I mean if you kind of think about it if these were scalars you know x would be b/a, but since they’re matrices we write the answer like this so A\b. So, it’s kind of like A is underneath the b, right, and so if I do that you can see that I get the same answer as when I did inv(a)*b. So that’s how you solve systems of linear equations in matlab, So now we’re going to talk about some other linear algebra concepts that you can do in matlab. One of them is taking the determinant of a matrix,, and so that is just a simple function called det, ok. So remember A = [3 2 -1; 2 -2 4; -1 0.5 -1]; from the last example we can also compute the eigenvalues of a matrix. So, iaeig and now you know when we compute the eigenvalues we usually want the corresponding eigenvectors. So one interesting thing about matlab that differs from other languages is that what is returned by the function is not set in stone, its dynamic. So if we look at the documentation for the eig function we see that if there is one output parameter it returns this little e, and the matlab documentation says e contains the eigenvalues of the matrix a. But, say I want the eigenvectors also so you can see these different function signatures. So if I assign the returned values of eig to two different variables I can get back let’s read here a diagonal matrix D of eigenvalues in a matrix V whose columns are the corresponding right eigenvectors. So the eigenvalues are going to be returned in a matrix called d, and the eigenvectors are going to be a columns of the matrix V. So let’s try that. [V,D] = eig(A) so we get a diagonal matrix D which has the same eigenvalues as before, and then the eigenvectors are all in V. So let’s just confirm that the definition of eigenvalues and eigenvectors holds, so A*V should equal V*D right, and so here’s another thing interesting about MATLAB is that if we want to check if two things are equal we can generally use the == as we do in regular programming. So 1 == 1 is 1 which means true, 1 == 0 is false. So if we do A*V == B*D we get false which is surprising because they should be equal given that that’s the definition of eigenvalues and eigenvectors, but we have to remember that there is always in programming some round off error. So if we subtract A*V – V*D we should get back a very small number, alright. So, we do that we see 1×10^14 which is indeed very small, so for all intents and purposes they are still equal even though equals equals returns false. Now so that brings us to the next thing I want to talk about which is so we have this matrix A times V minus V times D which kind of represents all the differences in those two matrices, and so we want to ensure that all the values are small. Now there are nine different values in this matrix so it’s kind of hard to tell how big or small it is collectively. So one thing we want to do sometimes when we have vectors or matrices is we want to calculate the distance from the origin, and so we can do that with vectors with matrices we call that the norm, and so typically all the elements so in a euclidean space for example it’s all the elements squared, added together, and then you take the square root. So in matlab there’s a function called norm that does this. So let’s just see what that gives us. So it gives us one very small numbers, so 5×10^-15 which we again can use to confirm that it’s very close to zero, so A*V is very close to equal to V*D, and if you remember from your math courses there are different kinds of norms. So I talked about the Euclidean norm which is a norm 2, we can actually do a p norm which is so instead of taking the square and summing them all together and taking the square root we do every element to the power of p, sum them all together and take the p of root, and that’s just the second argument of norm. So if I put a 2 there I should get the same answer because p equals 2 by default. So you can’t use P =3 you can only use P = 1 to infinity or fro, and so one would be the Manhattan distance.

Posted on

Learn Matlab Episode #4: Functions & Constants

Click here to subscribe for more videos like this!

QUESTION: What are the popular builtin functions/constants in MATLAB? How do you define your own functions?

So in this tutorial we’re going to talk about matlab functions and constants, so built-in functions and constants to be specific, and then how you can define your own functions later on. So by functions what I mean is mathematical functions like sine, cosine, tangent, exponential log, and square root and so those are pretty much what you’d expect if you’ve ever coded in any other language before. So I can do sine of 0 is going to be 0, I can do cosine of 0 gives me 1, tangent of 0 of course would be also 0. So let’s look at these trigonometric functions for a little bit. So one thing is that because matlab works on matrices I can actually pass in more than just one number into sine. So suppose I use the matrix grid before 1,2,3,4, if I pass that to sine what that does is it calculates the sine of every element of A and returns a matrix the same size as A. So I can do all that separately of course just to show that it is indeed doing that individually for every element and so all matlab functions generally work like that. Some other functions you might want to use is the exponential function that’s exp, there’s the log which is the opposite of the exponential. If I do log of exp of one I should get back one. I can do square root is sqrt ok, so those are some very simple elementary functions in matlab. There are also some built-in constants into matlab that you should know about. So, for example, pi that’s just pi. So if you do something like have a variable called pi and you assign it to something else, now I cannot use the original variable pi anymore. So what I would do if I want pi back is I would go into my workspace and delete pi alright, and so now if I type pi again it’s now back to original pi. Generally, I would avoid overriding built-in constants. So, one weird thing about MATLAB is it doesn’t have a variable e, so if you want the variable e you actually have to do exp of one which is e to the power of 1 which is e. Another important constant is i. So if I do the square root of minus one I get 0 plus 1 times i. I can also just type in I and it would give me the same answer. So you can also do things like i*i which should give you -1, or you can do i^2. So you do exponents using the hat symbol so that also gives me -1. So there are also some important functions for initializing matrices that you should know about. So the first one is the I function. So you’ve seen I in the sense that if I have a matrix A then A*I should equal A, and so I is the identity matrix and it’s a square matrix with ones on the diagonal and zeros everywhere else. So suppose I want to create a 3 by 3 identity matrix. I could do something like this which would be a little bit inefficient right, or I could do eye(3) which gives me the same thing. Another thing you might want to do is create a matrix of all zeros, so that’s just the function zeros. So that gives me a three-by-three matrix of all zeros. If I want to specify different dimensions, so I don’t want it to be a square, what I can do is I can pass in multiple dimensions. There’s also a function called ones which does a similar thing it creates a matrix of all ones. You can pass in the size the same way. So the next thing I want to teach you guys to do is how to define your own functions. So generally you want to for every function you create you wanna put it into a new file, so I’m going to go new function. So it gives me some boilerplate code that I could use and this is good because it will help me explain the syntax of a function to you. So when we create a function it starts with the word function. If your function returns things you can specify the output arguments over here. If there are more than one output argument you can specify it as an array. If there aren’t any output arguments you can get rid of this part completely, and if there’s only one output argument you can get rid of the brackets. So let’s suppose I want to define the hyperbolic sine function which matlab probably already has but we’re going to do it anyway. So it’s going to take one input argument called X and take an output of the Y. So matlab has some useful syntax highlighting it will give us a warning you know stating input argument X is unused since we haven’t written any code yet, and then it’s returning a value Y but we haven’t set Y to anything yet. So let’s save what we have so far, you can do command s or go to file save. So we’ll save it. So one thing to notice you have to save the function name has to be the same as the filename, and so like I mentioned before matlab already has its own sine H so we don’t want to overwrite matlab sine H. So we’re going to call our sine H something else, I’m going to call it my sine H. I’m going to rename this file to my sine H. Alright, so now I’m not getting that warning anymore. Ok, so we’re going to define our own hyperbolic sine which is defined as the exponential of the input, minus the exponential of the negative of the input, and then taking one half of that, so let’s do that. So inside the function I have to set Y remember because I was getting a warning that Y was not set. Remember, I want to put a semicolon here so that I don’t see the output of this expression. I’m going to get rid of this comment because this function is pretty trivial but in general if you have a complicated function you should probably comment it so you remember what you were doing later on or whoever else is reading your code will understand what you’re doing, and so you can write comments using the % sign to comment code. So I’m going to save that, I’m going to use this function so my sine H let’s say one, zero so we can see from this image that hyperbolic sine crosses zero and then it increases as x increases, so that’s what you should be seeing. Remember that matlab works with matrices though so if I wanted to I can say X goes from 0 to 10 and I want to calculate the hyperbolic sine for all of those values I can just pass in X and I’ll get back hyperbolic sine for all of those values. So that’s how you define your own function, probably yours in the future will be more complicated than that but hopefully that was a useful simple example. So we’re going to do one more function example here it will illustrate some new concepts. So I’m going to instead of going clicking the new button and choosing function I’m actually going to right-click on the workspace and I can see an option to create a new file and I can create a new function that way. So I’m going to call this new function is even and so you can see matlab has already replaced so before when we created a function from a new file it called it untitled, but now that I’ve given it a name to start matlab already knows to change the function name to that name. Ok, and I’m only going to have one output argument again so I can get rid of these brackets. The input argument is going to be X, and I’m going to add a comment returns 1 if X is even. Ok, so if you’ve done programming before you’ve probably heard of the modulo operator although I haven’t mentioned it in this tutorial series yet it does exist in matlab, so in matlab because the % sign is used for comments we do not use the % for modulo, if you’ve done that in c or java before. So instead we use modulo by calling a function called mod. So, basically it returns us the remainder. Ok, so this should be very simple. We want to return 1 if X is even so we know we want to mod 2, so y = mod(X, 2). Ok, but we have a problem here because when you take the modulo of an even number with two you will get 0, but if you take an odd number modulo 2 you get one so that’s kind of the opposite of what we want, but what we can do is we can use the utility operator which does a logical negation. So, until the 0 gives us one, until the one gives us 0, so what we want is to put the tilde in front of the mod, ok. And so now if I call is_even(1,2,3,4,5) we should get ones in the spots where the input is even which we do. So for 2 and 4 we get 1, for 1, 3 and 5 we get 0.

Posted on

Learn Matlab Episode #3: Basic Arithmetic

Click here to subscribe for more videos like this!

QUESTION: How do you perform basic arithmetic in MATLAB?

So in this matlab tutorial we’re going to go through some basic arithmetic in matlab. First I’m going to talk about the usual operations you see in programming which are plus, minus, multiply, and divide, and also the use of parentheses. So I’m going to first create some matrices for us to use, OK. So suppose I want to add two matrices, that’s very simple A + B. I want to subtract two matrices A – B. I want to multiply two matrices that’s A * B. So one thing to note about multiplication is this is pure matrix multiplication which means the inner dimensions of the matrices of A and B have to match. So, for example, if I create another matrix which is, if I create another matrix which doesn’t have the same number of rows as it has columns it’s not going to work. So, the size(B2) is 3 by 2 and the size(A) is two by two, so if I try to multiply A * B2 I’m going to get an error that says inner matrix dimensions must agree. So this does mean though I can do this, right? So, I transpose B2 it’s 2 by 3 and so a two by two matrix times a 2 by 3 matrix will give me a 2 by 3 matrix. So you can also divide matrices with the forward slash, but if you remember from linear algebra there isn’t really a matrix division like that. So, if you want to know what it means you can look it up on the internet, there’s a forward slash division for matrices and there is also a backslash division which we are going to cover in a later tutorial. By the way, if you want to divide two numbers that’s very simple we use the / for that. So the next thing we’re going to talk about is order of operations. It’s generally what you’d expect, anything in parentheses happens first, and then multiplication and division, and then addition and subtraction. So if I have A + B * C I would get that. So if I did B times C and I assign it to a variable D and I add that to A I get the same thing. So you can confirm that the multiplication is happening first. If I wanted the addition to happen first I would put parentheses around them, so we can confirm that what happened in the parentheses came first. So another thing you might want to do when you’re implementing an algorithm or writing some code is element by element operations. So we’ve looked at matrix multiplication which kind of does you
know if you’re looking at row I column J of the output that actually does a dot product between row I of the first matrix and column J of the second matrix. Something we want to do often when we’re coding is element by element multiplication, and so that lets just look at what we have for A & B again. So that’s pretty simple in matlab you just put a .* and so it multiplies each element by each corresponding element in the other matrix. This also works for division so a ./ So if you remember from your linear algebra classes there some different types of multiplication that you can have when it comes to matrices and vectors. First one were going to talk about is the inner product. I have x = (1, 2, 3) y = (4, 5, 6) and I want to do an inner product between these two vectors. One way to do that is simply by using what we already know. So x is a one by three vector and y is a one by three vector and I want the result to be one by one which is a scalar that means I can transpose y and multiply x by y as matrices, right, and so that would be 1 times 4, plus 2 times 5, plus 3 times 6. Another way you can do the dot product in MATLAB is by using the dot function. So we will cover functions more in a later lecture but I will introduce you to some today. So another product you might be interested in is called the outer product, and so that would be just the opposite of what I did before. So instead of transposing y and leaving x alone I’m going to transpose x and leave y alone. So that would give me a three by one vector times a 1 by 3 vector, and so the result would be a three-by-three vector. So that’s the outer product and there is no function for outer product in matlab, and so one thing to note is that usually when we represent vectors when you’re reading a textbook or sitting through a lecture, the vectors are column vectors so they have many rows but only one column, and so that’s kind of the opposite of what I’ve done just now, and so for the inner product you usually see x transpose times y and then for the outer product you see x times y transpose. So, just the opposite since I’ve been using row vectors. Lastly, there is the cross product and so the cross product is the magnitude is the magnitude of the first vector, times the magnitude of the second vector, times the sine of the angle between them, and then you use the right hand rule to determine the direction of the result. Alright, so dot product or inner product is not a vector so it doesn’t have a direction, but the cross product gives you back a vector and so that’s pretty simple to do in matlab, also. It’s just a function called cross.

Posted on

Learn Matlab Episode #2: Basic Syntax

Click here to subscribe for more videos like this!

MATLAB Basic Syntax Tutorial

Welcome to this matlab tutorial. This matlab tutorial is going to be on the basic syntax of matlab. So I’ve already opened matlab and this is generally the screen that you see most of the time. So the big main window’s called the command window, you’ll be working here most of the time. You can view your variables in the workspace on the bottom left, and you can view your current directory on the top left, and so that will tell you where in the file system you currently are. So, if you want to open a file from there you don’t have to type in the absolute path you can just type in the filename directly, or if you save a file that’s where it will go. So we call that the working directory and you can change the working directory to keep all your projects separate. So, you can go into the path up here and you know type in another path if you want to use the path for your particular project. So in matlab there are three basic types of numbers that you’ll be working with, or variables, that are all actually matrices. So you have scalars which are just plain numbers, you have vectors which is kind of like a list of numbers, and then you have matrices which are tables of numbers. So as I’ve mentioned before in matlab all these variables are represented as matrices. So if I do something like x = 5 you see that in a regular programming language you might just think of this as x = 5, but I can do something like check the size(x) and I see that it’s actually a 1 by 1 matrix. I can create a vector, we use square brackets, and you don’t need commas but I’m going to use them and so that creates a vector with the v = [1,2,3]; So if I do size(v) it’s a one by three vector, or you can also call it a one by three matrix. So this brings up some other interesting points about how matlab syntax works. I mentioned that you don’t actually need the commas so we can just do that and matlab knows that we want one by three matrix with the elements 123. So you also notice that I added this semicolon at the end of the line and what that does, it’s easier to see if I just don’t do it, so it prints out the last thing. So if I don’t use the semicolon it’s going to print everything out from the previous command, but if I do use the semicolon it will suppress the output. So, that’s why I didn’t put a semicolon after size(v). If I did I wouldn’t see anything. Now we’re going to go on to look at matrices, So it’s very similar to creating a vector except we need to have a way to separate each row, so that’s done with a semicolon and I’m not going to put one at the end so we can see the output. And so what that does is it creates a two by two matrix now with the elements 1234 in the variable A, and if I do size(A) it’s two by two. So those are the two things we’ve learned about initializing vectors and matrices that you can use commas to separate columns but you don’t need the commas you can just use spaces, and to separate rows you can use semi-colons. Another thing is that when you’re working with matrices and vectors
and you’re multiplying them and stuff like that, the dimensions of the vector are very important. So, typically you know you work with a column vector not a row vector like the one I just created, and so we can easily transform the previous vector which was a row vector into a column vector using an apostrophe and so that does a transpose. And so you see now that v used to be a one by three vector and now it’s a three by one column vector. You could have also initialized it using semicolons of course. Ok, so the next thing I want to talk about is how you can access elements of a matrix. Typically that’s done using parentheses and then indices and commas in between. So if I want to in general access the i row in the j column it would be a(i,j) So if I want a(1,1) for example I would do that. If I want a(1,2) and so on a(2,1), Another interesting thing you can do is access a vector within a matrix. So let’s say I want the first row of the matrix a, I can use the colon syntax to get the first row. So I’m going to put a 1 where I choose the row, and then I’m going to put a colon in the choice for column which means return me all the columns in row 1. So if I do that I get 1 2 which is the first world of A. Similarly I can use the colon syntax to get an entire column of A. So let’s say I want to choose the second row, or sorry the second column, so let’s say I want to choose the entire second column, I would do that. And of course if I do a colon in both parts of A it will just return me the entire A. So let’s create a bigger matrix now so I can better illustrate my next point. Alright, so I just created a four by four matrix. So the colon syntax can also be used to access ranges. So if I want I look at A it’s 1-16. If I want the part of A that has so a sub matrix that has the 6, 7, 10, 11 I could access that part by choosing the second and third row in the second and third column. If you’ve programmed before usually when you’re working with vectors, matrices, and arrays they’re zero indexed, in MATLAB it’s one indexed. So, a 1-1 returns me the first element, it’s not a 0-0. Another cool thing that we may use later is the colon syntax can be used all by itself it actually just creates a range. So if I did something like 1:10 gives me back all the numbers from one to ten, and so say I want to assign this to a variable, let me check the size of W, so that creates a row vector with the elements 1 to 10. It’s simpler to do than typing one through ten manually, right. So just to extend this a little bit we aren’t limited to only scalars, vectors, and matrices in matlab. You may have heard of a data structure called tensors, and so those are multi dimensional matrices, so it’s not a table it’s more like a cube or a hypercube. So you can instead of having a two by two matrix you can have a two by two by two tensor.

Posted on

Learn Matlab Episode #1: Installation & Resources

Click here to subscribe for more videos like this!

QUESTION: Where can you get MATLAB, add-ons, help with questions, etc?

Today we’re going to talk about, what is matlab, how do you get it, various add-ons and toolboxes you can purchase to extend the abilities of matlab, and generally how how you can get help using matlab. So the first thing I’m going to show you is just I’m going to Google matlab, and right at the top you see matlab’s official website. So that’s where you can go to get matlab and learn a little bit more about it just by reading on your own. To give you a short introduction though, matlab stands for matrix laboratory. So if you’ve ever programmed before it’s a little bit different because matlab is mostly for math and all the variables are matrices, even scalars are matrices. Matlab is usually used in academia and research so if you’re taking a university course which involves numerical computing you’ll probably use matlab. If you’re doing research and you’re analyzing data your professor probably already uses matlab and everyone in your lab as a result will be using matlab. Matlab is used in fields of engineering, science, finance, and economics. At its simplest matlab basically does calculations so it’s like a very fancy calculator. On top of that though, you can write code to evaluate a complicated formula, you can plot equations and data, and you can implement algorithms. Ok, so let’s talk about getting matlab. So I’ve already opened the website, if you scroll down to the bottom, or near the bottom, you can see a section called try or buy. So you can try matlab for free probably a trial that lasts 30 days…let’s check. It doesn’t say you have to enter your email but it’s a limited time trial so it won’t last forever. If you want to buy matlab there are several options. So the standard matlab you probably don’t want to use its over $2,000, and if you’re part of an educational institution you can use the education tab and get matlab for $500, the home version is just for personal use that’s a $149, and the student version is $49 so you probably have to go through some process to prove that you’re student. Another way that you can probably get matlab is if you are a student at a university there are options that the university has for you to get matlab, so you have to consult with your University’s resources such as the website or the bookstore to see if you can possibly even get it for free. For this tutorial I’m going to be using the 201 a version of matlab. So one thing you’ll notice is for the home version and the student version is they have these add-on products that you can get for a price. So add-ons are also called toolboxes and they have functionality and code that can be useful for you in your specific field of work. So, for example, if you do bio informatics you may want to purchase the bio informatics toolbox. So you can click on the links and get an idea of what’s included in the packages, maybe you do bio informatics and you don’t really even need the functions that the tool box comes with, so you might not want to purchase it. But, in general you can browse the documentation for free so you can see everything that you would get if you did purchase the toolbox. It’s essentially an API, so you can look at any function see what the input and the output is and decide if that’s useful for you. The next thing I want to talk about is how to get help with matlab. So you’re already taking this course and you’re going to learn a lot about matlab here, and when you start coding they’re probably going to be some very specific things you want to do that you don’t know how to do yet. So one place you can go I clicked on the community tab on the matlab website and so you can see there is a community of people who use matlab who post on this site. The file exchange I’ve used before people post useful functions and code that you know you may need in your projects that can be useful. There’s also a section called matlab answers where people ask questions and you can answer them or you can ask a question and someone else can answer you. Personally, I would recommend just searching your question on Google because they’ve already indexed all this stuff you could potentially put your question in the search box on the matlab site as well though, and you might on Google also get stackoverflow results so it wouldn’t only be matlab central which might be helpful.

Posted on

Python 3 Final Project

Enroll in The Complete Python 3 Course: Beginner to Advanced!

Click here to subscribe for more videos like this!

Alright guys, welcome back. We are at the end of the second section for this course which means you guys have a basic understanding of Python. You actually have enough right now to build some basic programs. Now, you might be thinking well, hold on, we didn’t even do that much. That might seem like it’s true but we’ve learned some core principles and concepts here as well as the language syntax, so far. So, we currently know how to create loops like while and if, or while and for loops, we know the if else statement, we know how to create strings and all the different types like Booleans, and numbers, and we also know how to set variables, among some other stuff. So, what we’re going to do right now is for the project for this section we’re going to put most of what we’ve learned in this section and we’re going to build a calculator program. So, I’m going to open up Chrome here and we’re just going to search Python calculator, just to see you know basically how we might write a calculator, so this looks good. So as you can see in the top of the script their defining for functions, one for addition, subtraction, etc, and each one of them is going to take a limit of two numbers and it’s going to return the result of the chosen mathematical equation between the two numbers. So that’s going to be the same for multiply, divide, everything and here’s where the actual program is going to start to output/input. So basically it’s going to say select an operation and it’s going to tell you what each number is equal to, and then it’s going to create a variable called “choice” and it’s going to use an input function which basically allows the user to type something in that hit enter and whatever the types can be stored choice. So this is going to be the prompt, so this is going to print out before the input so basically it’s gonna say enter choice 1, 2, 3, 4 and then whatever the user types after that it’s going to be stored in the variable choice, and then they’re creating two other variables, the first number and the second number, and for each is going to ask you to enter the number. So, first you enter the type of math you’re gonna be doing, and then you enter the first number, and then you enter the second number, and once you enter here what it’s going to do it’s got everything it needs, so it’s going to use an if else statement to determine what your choice was so that it knows what function to call with the two numbers that you’ve put in, which is awesome, and you guys might be really excited to build this. But, we’re actually going to go a few steps further, and the reason is if we open up a calculator you’re probably going to know that I wasn’t asked right off the bat what mathematical operation I want to perform, it just loads up with the number 0, and then I can type a number so let’s say 50, and the mathematical operator which we are going to use multiply, then two, we’re going to enter and we’re going to get a 100. Now with the ending of the math equation here you’ll notice two differences between this program and the Python script in the background there, and that’s that it didn’t quit, and actually we can continue to operate on the result of that first equation. If I want to add 75 I’m going to hit + 75 and hit enter and it’s going to add it to the result. If i want to multiply that by 2 I just hit x 2 and it’s going to multiply by that. So this is a continuous mathematical operation where the Python script allows you to perform one operation and is limited to two numbers, and it’s not very efficient, and I guess very simple. So, that’s good but we’re going to go a little more advanced. So, go ahead and open your IDE. What we’re going to do here is we are going to be using the regex library, so we’re going to import regex, and we’re going to print out the name of our program and it’s going to be called “print(“Our Magical Calculator”)” Now right off the bat we’re going to create two variables, so “previous = 0” and what this is gonna do is the previous variable is going to hold the result of the previously calculated equation, so we’re going to set it to 0 because we haven’t done any math yet, and then we’re going to create a variable called “run = True” You guys can probably guess what this is gonna do. Now, we need to create a loop for our program so we’re going to type “while run”: and we’re just going to call a function called “performMath” Let’s go up here and create a function called “def performMath” So the first thing we need to do is be able to accept input from the user to type in something, so let’s go ahead and type “equation = input(“Enter equation:”” and for now we’re just going to print out whatever they type so “print(“You typed”, equation)” hit save, now let’s run this. So I’m just going to print “Hello World” and it says you’ve typed Hello World, and then it drops back into the prompt. So going to type “Again typing something” and this is going to loop forever because we haven’t created a way to stop it other than, you know, closing the terminal window, or hitting stop right here. So, what we’re going to do now is create a way to end or quit out of this application. So let’s go ahead and “print(“Type ‘quit’ to exit\n”)” so let’s save that, Now what we need to be able to do is if they type “quit” we want to be able to you know actually quit out of the program. So what we need to do is we need access to the run variable in here, so for example let me just do this first. “if equation == ‘quit’:” let’s go ahead and set “run = false” “else:” print out whatever we typed. So go ahead and save and we’re going to run this. So we can type “Hello” and what it’s doing is this we didn’t type in quit so it’s not doing this instead it’s doing this. So let’s type in “quit” it’s not doing anything. So, basically what’s happening here is this is variable scope. Basically, to explain this this is a variable we created the top level of our program, so not defined in any functions or anything. We are in a function here and we’re in an if statement so we’re further into the code and we’ve stated run equals false. Now this is not going to have any effect on this very well it doesn’t have access to it. So, what we need to do first is actually get that global variable into this function. The way we do that is just at the top of the function type “global run” and then the name of the global variable you’re trying to get access to. Let’s go ahead and save and restart. So you’ll see we can still type in stuff but soon as I type “quit” it actually exits. So that’s what we wanted to do. Now, let’s go ahead and restart this. We’re expecting equations to look like this. So, how can we do that? Well, let’s actually how can we do that without creating a limiting set of functions that will perform operations, what if we want it to do this, you know, or what if we wanted to do this? In the script that we just looked at this wouldn’t be possible because we can only use two numbers and they’re each collected in their own variable, So what we’re going to do is we are going to use a built-in function. So actually what I’m going to do is grab access to the previous global variable as well, going to set previous here “previous = equation” then if we go ahead and rerun this, well we see it still says you’ve typed 80+2, or you’ve typed you know whatever the equation was. So we want this to perform math and what we’re going to do is we’re going to use a built-in function called “eval” So let’s go ahead and type that here “previous = eval(equation)” and then let’s save, let’s restart, and you’re going to see that before it prints out the result, or whatever we’ve put in, it’s going to evaluate it. So this is going to be able to perform complex mathematical operations from strings. So we can literally type in “80*100+42-10+78*142” hit enter and it’s going to calculate that up, and it does it in the correct order. So we all know that multiplication happens before addition and the evaluate statement our function actually is aware of that and it does that for us. You might be thinking, well that’s awesome, why don’t you know in those basic calculator examples why don’t they just use the eval function? The reason is because the eval function is actually supposed to be avoided because it can be dangerous. So, let me show you why. I’m going to print out here “print(“Hello World”)” you’ll see what happens is when it evaluates actually if we type in Python code here it’s going to execute that. So, let me go ahead and set “global run” see so we can actually crash it as well. Now this is going to work as long as we assume that our users are going to be performing math equations, but what if they are not? Well, because of this we are actually going to do this. So go ahead and “equation = eval(equation)” is going to be equal to the evaluation of equation. Actually, hold on “previous” Okay, so what we need to do first is perform regex on it, so we want them to only be entering mathematical symbols or numbers, we don’t want them to be able to type anything or to issue commands. So the way we do that is basically let’s create a new variable, actually let’s assign here we’re going to be entering our regex so “equation = re.sub( ‘ [a-zA-Z,.()” “] ‘ , ‘ ‘, equation)” “equation = re.sub( ‘ [a-zA-Z,.()” “] ‘ , ‘ ‘, equation)” So we’re going to remove everything except you know well everything important. Let’s actually go ahead and also remove the colons, we’re going to replace it with nothing, we’re going to do this equation, so we go ahead and show you what I mean. We’re going to rerun this and I’m going to say, “Hello 6 World” and what happens is going to strip everything out of that before it evaluates it, so it’s only going to accept numbers or as you can see you know the plus symbol, sorry, plus right there, let me remove that, alright. There you go. So “5+11×2” is 27 because 11 x 2 is 22 + 5 = 7. So, we’ve already got an awesome calculator but it doesn’t look quite right. So what we’re going to do is we’re basically just going to put an if statement, it’s only going to ask for you to enter equation if there’s no previous. So what we’re going to do is actually “equation = ” “” here, we’re gonna go ahead and say “if previous == 0:” it’s gonna put that otherwise equation is going to be “else:” “equation = input(str(previous))” So let me go ahead and the first time it’s going to ask for an equation, so “4+3” and then it’s is going to drop down and we can go “-1” and you’ll see that it doesn’t quite work. So, what we need to do is we need to tell it if it is, let me separate this here, there. We want to evaluate it separately if there’s a previous result or not. So what we need to do is let’s go ahead and “if previous == 0:” we’re actually going to do this “previous = eval(equation)” which is going to only evaluate whatever we type in. “else: previous = eval((str(previous) + equation)” “else: previous = eval((str(previous) + equation” Go ahead and save, restart, we’re going to go “4+4” equals 8, “-2” is 6, “*10” is going to be 60, and you can see that we’re actually using different types of math on it. So “+5-2+3” is 66. So this is what we want, but let’s just remove where it says you typed because we no longer need that. “3-2” is 1, “+56” and you can see that now we can really get into the math here. You can evem type, let me start that again, so you can perform basically any mathematical operation here, and when you’re done just hit “quit” Now we wanted to give a specific message when it quits, so let’s just drop down here and have it print out “print(“Goodbye, human.”)” Go ahead run it and we type “quit” you’ll see it now says “Goodbye, human.” and then it closes. So this is actually a completely valid program, and it looks a lot different from the other example that we looked at. Now the eval function can be dangerous OK, it very well can be, and that’s why what we’re doing before we evaluate anything is we’re making sure there’s no letters and there’s none of these characters in it, because if there were you know somebody could…let me open up this. I can’t do that, okay. Somebody could you know if they import the system and the OS modules that are included in Python they could end up damaging their system, and so by using regex to remove all that before its evaluated we’re keeping things safe. So thank you guys for joining me and congratulations on finishing the second section of this course. In the next section, in the next bunch of videos, we’re going to be learning more advanced concepts, and we’re going to be developing more complicated programs than this.

Posted on

Modules Explained in Python

Enroll in The Complete Python 3 Course: Beginner to Advanced!

Click here to subscribe for more videos like this!

Hey guys, what we’re going to do in this video is learn how to import different modules to a Python script and we’re going to learn about regex. So, what’s a module? Basically, it’s an external library that you can include and use in your project providing additional functionality without you having to write this additional functionality. So, for example, we are going to go ahead and “import re” which is the regex library, and that’s how you import something, just type import and the name of it. Now, re is included with Python and so there’s nothing that we need to install in order to use it. So, now the basic usage, but well let’s get into regex. So I’m going to go ahead and create a “string = “‘I AM NOT YELLING’, she said. Though we knew it not to be true.” Now basically regex is not part of Python. It’s kind of like a mini programming language that you can use in basically any programming language. So I mean you can use regex in Python, in PHP, in JavaScript, you know, Java, C++, so regex is basically a way to match certain characters and then do something based on that. Now as you can see on Wikipedia here, there’s standard libraries for .net, java, python, c++, and there’s some built-in for Pearl, JavaScript, etc. So this is not Python specific and we’re only going to cover it to a limited degree as we need it. So, in this instance we’re going to be learning a few things for in the next video. So let’s go ahead and start figuring out how to use regex. So, the first thing we’re going to do is you know if I “print(string)” you’re going to see it says ‘I AM NOT YELLING’, she said. Though we knew it to not be true.” So we’ve got capitals, lower case, we’ve got a period, comma, and quotations. So, let’s go ahead and play around with this a bit. I’m going to create a new variable called “new = re.sub ” and what we’re doing is we’re instantiating the re object that we imported at the top of the script, and we’re calling the sub or substitute function on the re object, which the sub is built-in to the re object. So just like calling any other function when you call a function on an object you need to put the parameters into the parameter list. Now, how we haven’t discussed classes and objects yet, and we’re going to get to that, but this is you know we need to know this for the sake of this video and the next one now. The three parameters that this substitute function takes is the matches that we want to make, what we want to replace them with, and then the string that we’re going to manipulate by doing this. So we’ve already got the strings stored in the variable named string, let’s go ahead and cover some matches. So let’s say we want to remove all the capital letters. So what we’re going to do is basically open and close square brackets “[ ]” now rules in regex are contained within square brackets. So if we want to remove all the capital letters I mean we could go “[ABCDEFGHI]” you know we could do it that way and list out the entire alphabet, but regex actually provides a way to not have to do that by allowing us to choose a range of letters so this is going to say any capital letter from “[A-Z]” we want to replace with nothing, and we wanted to do this on the string, string. Let’s go ahead and hit enter. Now, if I “print(new)” you’re going to see that it removed all the capital letters and left everything else intact just the way it is. So we can also do the same for lower case letters, so instead of removing all the capital letters, it’s leaving everything except the lowercase letters. Well let’s say we want to remove all the special characters. So what we do is actually we could put multiple rules inside of the square brackets. So let’s go ahead and put “new = re.sub(.,\’]’, ‘ ‘, string)” let’s hit enter, print it out, you’ll see that it removed all the punctuation from the string. Now let’s go ahead and combine this with the lowercase letters, and then additionally uppercase letters. We’re left with nothing except the spaces, can’t see them here but there are spaces here. Let’s go ahead and leave the lowercase letters just so you guys can see. There are spaces. So there’s about four right there, you know, and so we’ve got spaces. So let’s remove the spaces as well. How we’re going to do that is within here “new = re.sub(‘[.,\’A-Z+” “]’, ‘ ‘ , string)” “new = re.sub(‘[.,\’A-Z+” “]’, ‘ ‘ , string)” Now let’s go ahead and, let’s add actually, so let’s go “string = string + “6 298 – 345″ ” then let’s “print(string)”, and what you can do as well you can actually create “new = re.sub( ‘ [^0-9] ‘ , ‘ ‘ ,)” what we’re going to do here is we’re just going to tell it to remove anything except numbers, we actually need to put that in quotations, we’re going to replace anything that’s not numbers with nothing, and we’re going to perform that on the string. So if I “print(new)” you’re going to see that all that remains is the numbers, so that’s the extent to which we need to learn regex in order to do what we’re doing in the next video which is building an awesome calculator.

Posted on

Loops Explained in Python

Enroll in The Complete Python 3 Course: Beginner to Advanced!

Click here to subscribe for more videos like this!

Alright guys, so we are about to create a calculator program in Python and before we do that actually we need to learn a few more things. So we’re going to go over a couple of the loop types in Python, so there’s two. One of them is a for loop and one of them is a while loop. So basically a for loop is good for if you want to iterate over an array or a list in Python. You can do something for each item in the list, so let’s go ahead and create a list. So let’s just call it “numbers =” and we’re going to create array “[1, 2, 3, 4, 5]” So let’s type “for item in numbers:” and we’re going to just “print(item)” going to save and let’s go ahead and run this, and you’re going to see that on each line it prints out it’s number. So, we would be able to do this if we wanted to have different names in here. So, again, “[“Nick”, “Someone”, “Another Person”]” save this. Let’s go ahead and run the script again and it’s going to print out “Nick Someone Another Person” So what we can do here actually is we can “print(‘This persons name is”, item)” So let’s go ahead and you’ll see that for each one it does print out that. So that is a for loop and basically the second parameter here in the for loop is the array or the list, and then the first one here is what you want each item in the list to be called while inside it’s little block of code. So in this case we’re calling it item. So that is a for loop, now we’re going to learn about a while loop. So let’s go ahead and create two variables, one is going to be called “run = True” and the other is going to be called “current = 1” So let’s go ahead and what we’re going to do is type “while run:” and then we write what we want to happen you know if it’s currently running. So what we’re going to do is we are going to put an if statement here, so we’re going to go “if current == 100:” actually don’t need those brackets. Alright so if “if current == 100:” we are going to set “run = False” but if it’s not “else:” we’re going to “print(current)” then after we print current, “current += 1” Let’s go ahead and save this and what this is going to do is basically we’re setting run to true initially because we want it to run at least once, so while run which in this case the first time it goes over it’s definitely going to be true. It’s going to check is current equal to a 100. Well, on the first time no it’s not it’s equal to 1, so this block of code won’t run. If it’s not equal to a hundred what it’s going to do is it’s going to print the current number, and then add one to the current number, and then run is still true so it’s going to go over it again. So what we should see here is it’s going to print the numbers 1 to 99. So let’s go ahead and run the script, and that’s exactly what we see here. Now these are two useful concepts that we’re going to be using, so hold onto those, and if you didn’t quite understand what I’m doing here, let me know in the discussion section.

Posted on

If Else Statements in Python

Enroll in The Complete Python 3 Course: Beginner to Advanced!

Click here to subscribe for more videos like this!

Alright guys, now we’re going to be learning about some conditional statements in Python. So we’re going to be learning about the if-else statement, and this basically provides a way to evaluate if something is true or false, or if something is something, or it’s not something and can do something different based on which condition is true. So let’s go ahead and let’s set “check = False” and what we’re going to do with that is we’re gonna say “if check == false:” “print(“It is false”)” and I’m going to save this and this is the minimal you need for an if statement. We’re going to go ahead and run this and it’s going to say it is false because it is false. Now if we were to change this to true, and run the same code, it’s not going to do anything, and that’s because we haven’t provided and else. So if it’s equal to false it will do this otherwise it’s just going to do nothing. So let’s go ahead and drop back four spaces to where the if statement began, I guess, and that type “else:” and we’re going to “print(“It is actually equal to True”)” So let’s go ahead and let’s run the script and you’ll see that now where this is not the case, check is not equal to false, so then it’s going to do this instead. Now, what we’re going to do is this is good if you want two conditions, but what if you want more the two conditions? Between the if and else you can actually use something called “elif:” and here we actually need to supply a condition to the elif. So think of it like another level to the if statement, and think of the else as a catch-all like if none of the above are true than just do this. So if check equals false it’s gonna do that. “elif_check == “Hamburger”:” we are going to “print (“Yummm, hamburgers”)” and let’s throw another “elif_check == “Yo”:” and say “print(“Hello”)” So let’s go ahead and save this, we’re going to run it again, and as you can see check is equal to true. So it says is this true? Nope, move on. Is this true? Nope, move on. Is this true? No, move on. Okay, well the else is going to say well if none of the above is true them we’re just going to do this. So what we’re going to do right now is we’re going to set this to “check = Hamburger” and we’re gonna run the script, and you’ll see what’s happening is it’s checking this one first, that’s not true, so it moves on its like okay this one’s true so let’s just do this and then let’s get out of the if statement, so it doesn’t check any further. So that’s what an if statement is in Python and that’s necessary for what we are about to do.

Posted on

Return Values in Python

Enroll in The Complete Python 3 Course: Beginner to Advanced!

Click here to subscribe for more videos like this!

Alright guys, this is the last video in the subsection for functions and we’re going to be talking about return values from functions. So, again this is not new to some of you, to some of you it is, so if I mean it’s a pretty basic concept basically in the past we’ve created functions that do something in which case each time the function was called it printed something to the screen because inside that function that’s what we’ve done, we’ve told it to print. But, what if we want to return a value from the function and don’t want to print it out and do something else with it? So let’s go ahead and define a function, call it “do_math” and define two variables “(num1, num2)” It’s going to be a very simple function here, and we’re going to “return num1 + num2” Now, if we call “do_math” and pass in “(5, 7)” it’s not going to do anything because we’re not printing anything out, right. So what we could do is actually let’s create a variable called “sum1” or rather “math1” and this variable is going to include the sum of the two numbers that we pass in. So we’re going to call it a second time as well, “math2 = do_math(11, 34)” and we’re going to save it. Now when I run this function, or when I run this script, again nothing happened because we haven’t done anything with it yet. So what we’re going to do now is print out both results in one print statements. So we are going to say “print(“First sum is”, math1 “and the second sum is”, math2)” So we save this and hit the run button you’ll see that the first sun is 12 and the second sum is 45. So let’s go over this again so you guys, I’m not sure if I’ve explained it well enough so I’m going to do that again. We’re defining a function, we’re calling it do math, and we’re passing in number 1 and number 2, so there’s two arguments going into this function. Inside this block of code we are only returning the sum of num1 and num2, so in the case of the first sum it’s going to be 12. So we are returning to whatever part in our code we’re at, so this is going to become 12. So math1 is equal to 12 and then math2 we’re going to call that function again we’re going to pass 11 and 34 in and again it’s going to return to the spot right here with the value that we tell it to return with. So this line of code right here is going to become 45, so math2 equals 45. Then what we do we just print it out and math1 knows that it’s 45 because that’s what the result of that function is, and so this is going to be useful for a lot of reasons later on in programming. So in the next video we’re going to create a calculator using Python and it’s going to be a command-line tool, so we’ll be able to run it and perform different math operations.