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.