Python Tutorial - Functions




Hello this is NanoDano at with the next lesson in the Python Cookbook series. If you haven't seen the earlier videos in the series, check those out.

In this lesson we'll explore functions. We've already seen several functions. Print, input, and type are some built-in Python functions we've seen.

We also saw the randint() function which generates a random number. The randint() function came from the random module which we had to import.

Let's create a new Python file in our project and call it functions.

As we've seen so far, Python runs your script line by line from top to bottom. There are certain control structures, like the while() loop we saw which will alter the execution of a program.

We also saw the if, else, and else if, or elif, which can also make the execution skip over certain lines, or jump to a certain line if a condition is met.

Functions which are also a way of controlling the execution of a program and organizing code. Now we're going to see how to create our own.

The special keyword in Python is def, d, e, f, which is short for define. This will allow us to define a function. Let's create a function called greet_user which will, as you probably guessed, print out a greeting to the user.

We type def, space, greet_user, open paren, close paren. Our first function isn't going to take any parameters, so we won't put anything inside the parenthesis.

Just like the if statement and the while statement, we want to associate a specific block of code with this function. We do this by adding a colon to the end of the line that defines the function and then indenting the subsequent lines of code one level.

When you press enter after the colon, Pycharm will automatically indent for you. Then we can add a print statement saying hello.

Let's run the program. Hmm, nothing happened.

That's because all we did was _define_ the function. We are just telling Python, hey, this function exists. We aren't actually calling it though. The same way print and input functions exist, we have to call them before they execute.

Let's actually call our function now. We have to call it _below_ the definition so by this point in execution, Python knows what the greet_user() function is. To call it you simply type the function name with the parenthesis. greet_user()

Now let's run it. That's better.

Let's add another line inside the function. print("Welcome.") Let's put a blank line between the print statements. You can have blank lines within a function. What is important is the level of indentation. The whitespace matters.

Let's create another function called greet_user_by_name(). This time it is going to take a parameter. We need the user's name in order to greet them properly. Let's add a parameter between the parenthesis and call it name.

Then we can say print hello plus name.

Then let's call it. Let's put a name directly inside the parenthesis. Run it.

Let's modify the code slightly and put the user's name in a variable instead and then pass the variable to the function.

We could also use the input() function to ask the user for their name. We could also put input() directly inside the function parameters.

Functions can take multiple parameters. Let's modify greet_user_by_name to take a second parameter. The second parameter will be the greeting to use.

Let's modify the print statement to use the custom greeting, and update our call to the function.

When greet_user_by_name is called, it first evaluates the parameters. The input function will get run first and greet_user_by_name will not begin running until input() has finished.

A function in this form _must_ have all parameters present. You cannot call custom greeting with only one parameter. You need to provide all of them.

Let's take a second to clean up this code. First I want to use some white space to separate the function definitions and the main code.

Then I want to add some comments to document the functions. Three quotation marks is used to open and close a multiline comment.

Ok, this looks a little more organized and easier to read. I hope you will agree. You do not have to use the exact spacing I do with the blank lines, but it is important to keep the indentation the same, which is 4 spaces per level. Let's get back to the functions.

It is also possible to provide default arguments for functions. We can assign a default value to the greeting parameter by adding an equal sign and giving it a value, in this case, "Hello".

We can leave our call to the function exactly the same, but we can also remove the second parameter from our call.

When we do this, it will use the default greeting of Hello since we did not specify a greeting to use.

We could also provide a default value for the first parameter. Let's use the name "user" if no other name is specified.

Now we have a few options when calling the function.

We can call it with no arguments. It would then use the default arguments for both parameters.

We can call it by passing it the arguments in the order it expects. Name first and then the greeting. This will use both of our values instead of the defaults.

We can also call the function with the arguments out of order. If we put them out of order then we have to explicit and tell the function which argument is which. When we call it this time, we say greeting="Welcome" and name="NanoDano".

A little note about terminology. When you hear the term parameter, it is referring to the variable in the definition of the function. When you hear the term argument, it refers to the value being passed to a function when it is called. Although honestly, I tend to use the terms interchangeably.

The last topic I want to cover with functions is return values. Our greet functions perform some actions, like printing to the screen, but they do not return any values.

The input function we saw is an example of a function with a return value. When we call input, we store the value it _returns_ in a variable.

Let's create a simple function called cube with one parameter named base_number.

The code for the function is pretty simple. cubed_value = base_number * base_number * base_number. The asterisk, or star sign, is the symbol for multiplication.

So we have this variable called cubed_value, but it only exists within our function. When our function is done running, all of the variables created inside the function are destroyed, so we won't be able to use the variable cubed_value anywhere outside of the function.

What we want to do is return the value. This is how you get a value back from a function.

To do this we use the return keyword and give it the value we want to return. Return is not a function, so it does not take parameters, you just type return, space, and the name of the variable or value.

In this case we don't actually want to make a decision about what to do with the value. We don't know if it should be printed out to the screen, or used in some other calculation. We just want to return it to the caller and let them do whatever they want with it.

Let's call our function down below. cube(11). Leaving it like this would really have no effect because it would calculate the cubed value, but do nothing with it.

Let's store it in a variable named eleven_cubed

And then print the variable. Let's run it now and make sure everything works.

Yup, everything looks good.

When it comes to naming your variables, I recommend using a name that describes the variable. This is sometimes called "self documenting code" where your variable names and function names clearly describe what is going on to the point where you don't need to pull out the documentation to understand what is going on.

Using variable names like "i", "n", or "x" are valid names, but if you need to go read your own code months or years down the road, you may not remember what "i" was supposed to represent. There is no performance hit for choosing a longer variable name.

Let's commit the file to our local git repository and then push our changes up to GitHub.

Right click on the root folder in the project, and go to Git -> Commit Directory. Add a comment saying you are adding function examples and choose Commit and Push. Finalize the push so your changes go to GitHub and you are done.

Now you have some more reference material for your cookbook. Creating functions is something you'll do all the time and it will become second nature, but until that happens, don't be afraid to refer to your cookbook.

If you have any questions about this lesson please leave a comment.

In the next lesson we'll explore a new variable type called list.

If you enjoyed this video, subscribe to the channel and visit Thanks for watching and keep coding.