Skip to content
CBT Nuggets
DemoBook a Demo

Understand Functions in Python

This skill, led by John McGovern, delves into the fundamental concepts of using functions in Python. It covers the creation and utilization of Python functions, including built-in and custom functions. Key topics include the use of positional, default, and keyword arguments, as well as the importance of the return statement for returning values from functions. The skill emphasizes writing modular, reusable code and adhering to best practices such as the DRY principle.

Full skill from Python Functions. Preview the training IT teams trust.

Updated

54m

Skill 1 of 16 in Python Functions

What you'll learn

  • Explain how a reusable function lets you change logic in one place and call it as many times as needed in a script
  • Use the help() function to explore Python built-in functions such as print(), including its sep and end arguments
  • Create a function with the def keyword using lowercase, underscore-separated naming and the correct parentheses and colon syntax
  • Document a function with a docstring and display it using help() or by printing the function's __doc__ attribute
  • Compare positional, default, and keyword arguments by passing platform and hostname values to a device configuration function
  • Write a function that returns a generated value, such as an email address built from a username and a default provider

Free 54-minute video lesson with a full transcript and knowledge checks. No account needed to watch.

Overview

Join John McGovern as he covers the fundamental concepts around the use of functions within Python.

Recommended Experience

  • At least six months of Python programming experience is recommended, but not required
  • An understanding of concepts taught in Cisco CCNA is recommended, but not required

Related Job Functions

  • Network engineer
  • DevOps engineer

John McGovern has been a CBT Nuggets trainer since 2020. His areas of expertise include Python, networking, network automation, and cybersecurity.

Introduction to Functions

In this Nugget we take an introductory look at functions within Python!

Exploring Built-In Functions

In this Nugget we take a look at some of Python's built-in functions!

Knowledge Check

Which of the following is a parameter, used by the built-in print function, that will add a separator between strings to be printed?

Creating Functions

In this Nugget we learn how to create our own custom functions!

Knowledge Check

Which of the following is a keyword used to create a new user defined function?

Passing Arguments

In this Nugget we learn how to leverage positional, default, and keyword arguments within our functions!

Knowledge Check

Positional arguments cannot follow keyword arguments. True or false?

The Return Statement

In this Nugget we learn how to use the "return" keyword within our functions!

Knowledge Check

A Python function will return which value by default?

Conclusion

I hope this has been informative for you and I would like to thank you for consuming.

View Transcript

Introduction to Functions

0:00[AUDIO LOGO] Hey, guys, and welcome back to another skill on Python for network engineers. Functions happen to be a really common concept throughout programming, and by using Python, you're going to be using functions all the time. So what exactly as a function then? What are we talking about here? Really, at its core, just conceptualize a Python function as a group of code.

0:35And the type of code we're talking about can literally be anything. And we'll see this throughout the scale-- you can have really, really, really simple functions that just print out something. Now functions can be built-in. There's going to be built-in functions within the Python library. You can also have third-party functions, which you can install and import into your Python code. And we can also have custom functions written by us. Now like I said, most functions are simple a group of code, and that code can literally be anything.

1:05If the code can literally be anything, what is the advantage to using a function? Why put into a function? What is so important here? Well realistically, what functions do is it allows code to become much more reusable, and it makes your code much more modular. And using functions allows you to adhere to what is called the DRY principle. What is the DRY principle? Well it means, simply, don't repeat yourself. As opposed to just continually repeating the same type of code, the best thing to do is to put that code into a function, and then you can just call that code as many times as you need.

1:39Now another important concept to understand about Python functions is that functions will always return a result. And by default, that value is going to be the special value within Python, none. And we've talked about this value in previous skills. However, if we need our function to actually return something and not just none by default, then we are able to instruct their function to do so. And we'll be able to see how we can do that later on within this very skill using the return keyword.

2:10So let me just give you a short example to help you conceptualize the utility and usefulness of Python functions. How we have the ability to help us be able to achieve that principle of DRY, why don't repeat yourself, and why it makes your code much more modular and easy to manage. OK. So let's dive into Visual Studio code then. So let me go into my directory here. I'll say, cd Python-Net-Eng, and I'll go into my head and directory where my virtual environment is. And let just activate this. And I'll make a directory just called maybe, function-examples and we'll see the end.

2:45Cool. So I'm going to-- take credit. Let's clear the screen. What I'm going to do here is to create an example just called example1, super duper simple. And what we'll do is we'll open this in VS code then. Python-Net-Eng, function-examples, and we're going to example1. OK. So this won't be the most realistic example. It's just going to help you conceptualize the concept here. So let's imagine that we wanted to-- what will we do here? Let's imagine that we wants to print out some type of warning, OK. Just say this device as owned by IPvZero system, if you access this without authorization, bad stuff will happen.

3:22OK. So let's say we have this warning here and we want to present this at the beginning of our message and at the very end. So what we can do is just print out some random text here, blah, blah, blah, blah, blah. It doesn't actually matter-- similarly blah, blah, blah. OK. Now the crucial thing is that we want to have this message at the start and at the end. OK. So what I'll do here is just copy and I'll paste that in again. So let's just save this. It's just now I'll run the script. So let me clear the screen for all of the stuff that we touched.

3:55And we'll say, python 3 example1.py. And hit enter. And as we can see here at the very top, we have our warning message, we have some text in between-- doesn't matter what that is. And at the very end, we close off the message with the exact same warning. So that isn't the most useful thing, but it's there and it has its purpose. We've got our warning at the top and our warning at the bottom. OK, so let's just say we want to change our warning message. And we can maybe say-- I don't know like, all devices in thus network are owned by and let's say the company name.

4:28It may be changed or something. Let's just say CBTN systems and just delete this part here. And we'll change the end here. And let's just say, do not touch, dot, dot, dot or else. It's some really ominous message OK. So as we can see here, our warning message has changed. Now because it's changed, we've changed it here, but we also have to change it here as well. So then I'd also need to alter the code at this part here. I have to go in and take all this away, just add all that. And I suppose I could, in this case, just use a copy paste job.

5:01But like I said, this is a very, very simple example. Now as we can see here, this warming statement is only being used in two areas of our code, in line one and line four. It really isn't too big of a hassle for us to just delete one and then maybe copy paste a little bit, and we're done. But can you imagine if the code was way, way, way more complex than this? And we had to update the code in multiple different areas. Having to go into each iteration of that code and make the very same change to all instances of the code really isn't very efficient.

5:33And it's also prone to error. So if you happen to maybe say CBTN systems and on the second one you're typing this again, and you'll say, system, then suddenly you have a difference between this part of the code and this part of the code, when, in fact, they should be the same. Now again, this is a really trivial example. But let me show you how we can solve this type of problem using a function. OK. So do not worry about the syntax here. We'll definitely go through the details as we go through this skill. What I'm going to do is create a function and we're going to call this function warning text.

6:03OK. And like I said, a function can literally be any type of code, and all this function is going to do a print out that warning statement. So I could just say something like, this network belongs to CBTN. Don't mess around with it. That's our new warning text. Now what we're going to do here is pretty much do the same thing, but instead of having to manually type this out, what we're going to do is to call this function. So what I'm going to say here is warning text. And what I can also do is just print out the blah, blah, blah, codes, and again, more blah, blah, blah, whatever.

6:35And at the very end of our text, we could just call the warning function yet again. So if I save this, watch what happens OK. Let's clear the screen. We arrow up and hit Enter. Look at this. We're getting the effect we want. That's network belongs to CBTN. Don't mess around with it. We get that warning at the top. We have a random text in the middle, and at the very bottom, we have the exact same code executing that print statement. This networks belongs to CBTN. Don't mess around with it. And here's the thing. If we wanted to update this, well, we just update it in one place.

7:07So let's just say this belongs to CBT Nuggets instead. Let's be a little bit more explicit. We don't have to change any of this code here. We don't have to change it in multiple places or do any copy and pasting. Just update this little function and that is what the code as referencing to now. So if I just arrow up, hit Enter, look at this. It's been updated in all the same areas. We don't need to worry about going into this part of the code, and then deleting this and adding and the new change. And then going into another line the code, deleting another part, and adding in another section. Because we have that nice, tightly defined, modular function, we can just make the change in one area, and we can call that function as many times as we want.

7:45Like I said, we can just keep calling it. Let's say, warning text, and if we save this, we can use this function as many times as we want. So this is what we're going to be exploring in this skill right here, the concept of functions, how we can use them, and how we can call them. What are the rules at play here? So we really do have a lot to get to within this skill. And how about we start by finding out what built-in functions that Python has to offer us. Well that's what we're going to be doing in the very next Nugget. So I hope this has been informative for you. And I'd like to thank you for viewing.

Exploring Built-In Functions

0:12Hey, guys. And welcome back. So in the previous Nugget, we had just taken a broad overview about what functions are and why we might want to implement them within our codes. What we also learned was that Python also has these built-in functions, which are ready-made and ready to be used. So what exactly is in this standard library of built-in functions? Well, how about we do a little bit of exploration, find out what these functions are, and what we can do with them? OK, so let's go and open up a browser. And what I'm going to search for is "python built in functions," pretty self-explanatory.

0:44So how about we click on this top link right here? And as we can see here, within the Python documentation, we have this chart of all of these built-in functions which are available to us. And as you can see here, it tells us that the Python interpreter has a number of functions and types built into it that are always available. We don't have to do any kind of installation. These are just built in straight from the installation of the language, effectively. OK, so straight away, we can see one of our favorites right here, the print() function.

1:15So we've seen this one many times. So let's just dive a little bit deeper into it. OK, so what we'll do here just now is we'll dive into IPython. And like I say, we've already explored this function here. We just say print, and we know this actually takes an argument. And the argument is going to be whatever we want to print, like, say, my name-- or rather, "My name is John." And if we pass this argument into this function, then this is going to be printed to the terminal here. OK, cool. But what if we wanted to explore a little bit more about what this function can do?

1:48What we can say is help, and then within parentheses, pass in the function we want to get information about. So basically we're saying, help, tell me about the print() function. So if I hit Enter here, as we can see here, there actually are some arguments which we haven't actually explored yet, things like sep and end. And we can actually see the way we can format this here. We have our function right here, which is print, as we happen to specify our value. That would be, like, "My name is John." And we also have an argument here, such as sep or end.

2:21OK, cool. So let's actually try this out, then. OK, now to get out of this, we can just press the letter q to quit. OK, so as we saw from the help page, we now have this new parameter that you might not have known about called sep. And we can follow the advice of the help page to explore this built-in function. And we can use this within our built-in function. So we can say print. We could say "john", "lauren", "paul" and that would just print out "john", "lauren", "paul". And like I said, let's make use of this sep parameter that we just found out about. We'll say "lauren" and we'll say "paul".

2:54And as per the documentation, we'll say sep is equal to, and we can just give it a value. And let's just put in a plus sign. And if we hit Enter now, look at the print statement. We're separating, all of these values, "john", "lauren", "paul". Everyone has been separated with this plus sign. So we're basically putting a plus sign in between all the values. So again, we could say "30", "July", "2006". And we could say sep, separate them with a hyphen. And hit Enter. Now we can separate all our values with a hyphen.

3:25OK, so there is the built-in function print(). And as we can see, we can get a little bit more information about our built-in functions by using our help keyword. So let's go back and check out a few more. OK, so we have one called isinstance(). Let's check that one out. How can we use this? Well, again, if we're unsure, what we can say here is say help is instance, and hit Enter. And again, it tells us this is help on a built-in function called isinstance. And what it's going to do is return whether an object is an instance of a class or a subclass.

3:57What does this mean? Well basically, we can test if something is a string, if something is a dict, if something is a list, so on, so forth. And the way we use this is in the form of a tuple. We say isinstance, and then we pass in what we want to evaluate. And then we pass in the data type, is this an instance of, effectively. So let's check this one out. Again, we'll push q. So what I can do is, for example, let's create a variable called number. And we'll say number. And let's make it a string value. We'll put it within quotation marks. And what I can say here is isinstance and then pass in what we want to test.

4:30We want to test our number variable. And let's check if this is an integer. So we'll say int. And if we hit Enter, it's going to say false because the variable number is not an integer. In fact, it's a string value. So we're getting a false. However, if I happen to update this, we'll say number is equal to the number 1. Again, this is an integer now. We're not using our quotation marks. I can say the very same thing as before, isinstance, a variable number, is this an integer? Cool. And that should be isintance, not instance-- isinstance, number, int, hit Enter.

5:04And this is true because it is an integer. Same again, we could say something like my_list is equal to all the eights, 192.168.1.1. And we can say isinstance, my_list. Is it a tuple? No, it's not. Is it a dict? No, it's not. Is it a list? Oh yes, it is. Now, this might seem a little trivial right now because you think, why can't we just say type? Because we know we can do this-- we can say type(my_list), and it tells us. Well, this built-in function isinstance is very good for conditional logic because, again, it's given us this nice Boolean value, true or false.

5:37So what we could do here-- just let me just exit this out. And I'll just create a quick example here. Let's go into example2. So what I can say here is my_list is equal to. And I'll say "john". And let's create a list of numbers. We'll just say 1, 2, 3, And we know from previous skills we can actually put lists within lists. So let's say we had a list, again, within this, a sublist. We'll just say 2, 2, 5, and maybe 6, 45, 78. It doesn't really matter. So let's say we wanted to test that the number 5 happened to be within this list.

6:09So we know we can use a for loop to unwrap those individual values. So we'll say for num in my_list. And what we can say, let's say we're looking for the number 5. We can say if num is equal to 5, then we'll print out, "The number 5 is present". So if we save this and rerun this script here, nothing actually happens. Why is the number 5 not printing out? Because we can see within our list, the number 5 happens to be right here. So what is going on? So what we can say here instead is just print out the nums before we run our condition.

6:42Let's see what we're actually getting. Aha. So as you can see here, we're unwrapping these values. But this one here is in fact a sublist. So basically, this element here actually requires a second round of iteration. So what we could actually use here is the built-in function isinstance right here. Watch this. We can say if isinstance, your number variable, if that happens to be a list object, what we're going to have to do is to iterate through again to unwrap that in our list. And I can say for n in num, and say if n is equal to the value 5, then we can now print, "The number 5 is present".

7:20However, if what we are iterating through is not a list, we can just say else, and we don't need to add that other round of iteration. We could just do a test straight from the get-go and say if num is equal to 5, print, "The number 5 is present". OK, so this example is a little bit clunky. But you can kind of get the drift. In fact, let me make that a double equal sign because it's a comparison. But as you can see here, we have this cool built-in function, which can pretty much say, as we loop through every item, if any of these items happens to be a list object, i.e.

7:50this part here, then we need to go through another round of iteration to unwrap the individual values within that list. And then we can test on it. However, if we don't have a list and it's just integer values, like these, we can just straight away test, is this integer equal to the number 5? So now what we can do here is run this test once again. And as we can see here, we're getting a hit now. The number 5 is present because we used the built-in function isinstance to test if we happen to have a list, which we do. and then, we further iterated through that sublist before running our test.

8:23So now we have the hit. So as you can see here, the Python built-in functions, there really are a ton of them. And there are so many useful cases where you're going to be using these functions. And no doubt you can probably recognize some of them already. We've used the id() function before, which gives us a unique ID for a place and memory. We can use the type() function to tell a particular type of a variable. Is it a dictionary? Is it a list? We can use the len() function. We've done that before. This can tell us, for example, how many items are within our list.

8:53And another one we've used before is the sorted() function. This can do many things, for example, sort elements within our list, which we did before. We've also seen the max() function and the min() function. So really, these built-in functions are going to be your best friend in so many cases. In fact, in this lesson right here on built-in function, we've actually been using a built-in function, the help() function. So I really would encourage you to explore all of these functions. Pick a few. Use the help() function. Find out what you can do with them.

9:24And test them out because you're going to find that in so many cases, these built-in functions have been built-in for a reason. They're going to solve a lot of your problems. So definitely check them out. Okeydoke, so I hope this has been informative for you, and I'd like to thank you, for viewing.

Creating Functions

0:12Hey, guys and welcome back. So let's talk about how we can write our very own custom functions. This is a super useful practice. You're going to use it quite a lot, and it's going to go a long way for you to be able to write cleaner code, which is easily maintained and much better suited for team collaboration. I like to say functions can be very simple. They can be extremely complex. It really depends how far you want to take it. Generally speaking, when applied to network engineering, functions tend to be not too complex. You typically want to perform a simple task and have as innate little reusable piece of code.

0:47Therefore you dump it into a function, and then you can just keep using it. So how about we dive in and see how we can create these custom functions. Before we start, what you might have noticed was that the very first Nugget within this skill, I wrote a short function. So let's just talk about this. This is the key what we're really going to be relying on. That's def key. This is crucial. This is basically how we define our functions, think of that as what it means defining a function. So the syntax is going to be used in this keyword, def. And then you're going to, in essence, choose a name for your function.

1:21Now, the kind of convention to name your functions is to use lowercase and to separate out your words using underscores. So something like maybe, my_function, and then what we're going to do is have an open parentheses and then a closed parentheses followed by a colon. And then, after that, we're going to write our code as an indented block within this function. Now the convention is to use four spaces here. No, this is not a hard rule within Python. You can use one, you can use two.

1:52However, it is a pretty strong convention within Python to use four spaces if you happen to use something called a linter, which basically checks your code and examines it for potential errors and flaws. If you use maybe one or two or three or five spaces indentation, then the linter is going to show that. So to keep that happy, I would recommend you just use four like say as a bit of a convention. OK, so let's dive into our code then. So let's go into my directory, activate the ven, if can type this correctly.

2:23And let's go into the Functions-Examples, and let's create one called example3. OK, great. Let's go in here, OK, so let's first start with a really simple example, so how do we create a function? We use the keyword def, and you can see it's actually colored blue within my ID because this is a recognized keyword. And then I do a space. And no, this point here is were we're going to name or function. Again, the convention is to use lowercase. We don't want to be seeing capital letters here. We want to be doing something like, say, my_test_function.

2:54And again, we separate out words using those underscores. And then we're going to say open parentheses and close parentheses, and then our colon. Now, if you're using something like, say, Visual Studio Code, if you just hit enter, naturally, it's going to indent your four spaces here because it knows to do this. And like I say, we can do any type of code within this indented block like just say, welcome to CBT Nuggets. OK great. Now to call this code, the important part is that we don't do it within the indented block here. So we have our indented style that will have one, two, three, four, indentation.

3:28We want to go back out, so all we do here and go as many lines down as we want. From this point here, we can do what is known as calling the function. Now simply put, to call the function, all we have to do is to specify the function name followed by a parentheses, and that's all it takes to call a Python function. So say my_test_function, followed by parentheses, and if we just save this example3 and we'll say Python3, exampl3.py hit enter, and that's no printout.

3:59OK, so not a big revelation here, but let's expand on this. Now what I want to stress here is that even though we went out to the margin here, that was just to escape the actual definition of the function here. Once we're out of that, we can call it pretty much from anywhere. So let me just highlight what I'm talking about here. So let me just delete this here, and let me do a simple for loop. I'll say for num in range. And I can just say 0 to 4. And if I hit colon and then enter, that's going to indent me again.

4:30But what I can do here is I can call this test function, I can say my_test_function, and how do we call? We use a parentheses. Now, this is actually going to work, even though it's indented one, two, three, four as part of this code block here. It's not within the definition of the function. So as long as we escape that, we're going to be OK. So after I show you this here, and if we run the script, that should not print out multiple times. We should loop through it and continually keep calling the function. So arrow up, hit enter, and as you can see here, we've actually called that function multiple times due to a loop.

5:04So ultimately, we can't be part of this indented block when we're calling the function. Once we're out of this block, we're fine. Now you may be thinking, well, John, you told me about the print function, the belt and print function. That looks a little bit different when you call it. What is the deal with that? Let me just show you this. OK, so I'll just comment these out just now. So when we call the print function, now again because this is a special built-in function. We do get a little bit of color highlighting ground here, which we don't get for our regular functions. But notice this, we don't just call the function by saying the function name and parentheses.

5:37That's not how we use the print function. That is because the print function actually takes what is called arguments. It actually has to pass something into the print function, like my name as John, something like that. Now, as it transpires right here, a little test function doesn't take any arguments. So we don't pass in any arguments. However, what if we did want to add in some argument, we want to add additional functionality? How would we do that? OK, so let's delete this, and we'll create a new function. So how do we do that? You guess that we're going to see def, and now create the name of the function.

6:10So let's create a function just called adder. Now within our parentheses, we're going to specify the parameters we want to take. Now just conceptualize these as variables, which we can pass into our function. So to create my first parameter, I'll just get a variable name. I'll just say a. And then to add another parameter, I'll do a comma and add another variable name, so I'll just say b. And as before, we do our colon, and then if we hit enter, we get our indented block. So what we are seeing here is that when someone is going to use this function, they're going to have to specify adder and then supply something which is going to represent a, and then supply a second thing which is going to represent b.

6:53And within our indented block, we're going to specify what we want to do with these variables. We're going to be taking into a function, as [INAUDIBLE] function, we'll just do a print statement once again. And I should just highlight that not all functions are about printing. This is just the easiest way to get it going. So what I'm going to do is take the first argument, the pass in which as represented by the letter e, and I'm going to actually add it to the second argument, the person which is going to be represented by b. And quite simply, that is it. If we just go back out, we are indented again, and now we have defined our new function.

7:28So how on Earth do we use this function? Well, if we just say adder, and try to call it like this, this is not going to work because this other function actually takes two parameters. It takes one here and one here. OK. So let's check this out. OK, so we'll clear the screen, if we hit arrow up, hit enter. And it tells us straight away, we have a type error, but actually missing two arguments, a and b. So clearly, we need to pass in these arguments because the function has been defined as to accept two arguments. So let's check this out then.

7:58Now just to be clear here, we don't have to type a coma b. We can type anything we want. So if I type in the number 3 as the first one, that is going to be represented by the variable a, which means that we're going to pass in here. So we'll have 3 in this place, so we'll say 3 add whatever the place for b. So let's say for b, we'll pass in the number 7. OK. So all that is happening here is that we call this function here and are passing and the two required arguments.

8:29What this function is going to do is going to map this one to a, and it'll map this one to b, and then just do whatever the code said. Well, the code says then here, we have to print out whatever a plus b is. Well, a is equal to 3 in this case, and b is equal to 7. So we have to print out whatever 3 plus 7 is, which is equal to 10. And in effect, this other function has taken the arguments 3 and 7 and added them together. So let's check this out. Arrow up, hit enter, and our other function is printing out correctly the value 10.

9:02Now, what if we use the other function yet again? And if we passed in the variable John, which is going to act as the variable a, and we pass in the second string McGovern, which is going to take the variable b. What is the other function going to effectively do? Well, let's comment out this first call, and we'll just use the second one. OK, so clear the screen, arrow up, hit enter. Look at this. It's actually joined the two words together. And if I happen to reverse these and say McGovern, and then John, save you, arrow up, hit enter, then it's going to put them round the other way.

9:34That is because in this case, McGovern is mapping to the variable a, and John is mapping to the variable b. And what does the function say to do? It says add a first, so put whatever a is, which is McGovern, and add it to b, well, what is b? b is John. So let's add in to John here. So let's look at another example. We could create a function which would generate email addresses. So we can say def, and we just say create_email. Now we're going to pass in some type of arguments. OK, so let's say we wanted to have a username and a provider.

10:08Provider being like say outlook.com or gmail.com or cbtnuggets.com or protonmail.com, and the username is whatever username you want. Now, a good kind of practice to do here is to not just say a and b because they are pretty non-destructive. Even though you could use a and b. It's probably better to give the variables a kind of meaningful name. So we could say we want to have a username to be taken in, and then we could say, provider. OK, so we'll do a colon, and then we get our indented block.

10:41So whenever someone is going to call this function, they're going to have to provide two arguments that is going to be represented by the username variable, as well as the provider variable. So how do we actually want to manipulate these variables? Well, again, we'll just use a simple print statement for simplicity, and we'll use an f string. And what we'll say is, your new email is, and then we're going to take whatever username they pass in. So we'll pass in that variable here. And then we'll do the @ sign, because that's what we do for emails, and then we're going to specify the provider, i.e.

11:14as a @gmail as a @outlook. So we'll say provider, and we'll always just end each one with .com. So now, if we want to create an email, we have to provide two arguments. The first one that's going to be representing the username which you would put in before the @ symbol. The second argument we give is going to be represented by this provider variable, which is going to be inserted after the @ symbol here. OK, so let's try this and let's call this new function here. We'll say create_email, and I'll say my email as IPvZero.

11:46That's the first argument, which is going to be the username and then a comma. And I'll also add in-- my account is going to be, let's see, I don't know, Gmail. OK. So if I call this function-- I've given it my two arguments, that's what I need, let's see what happens then. OK, So if we arrow up, hit enter. Now, we have used this function to generate our email address, IPvZero@gmail.com. Now if you recall, when we dealt with Python strings, we talked about something called a docstring. A docstring is basically a string which is used for documentation, and it really is very often used within our function.

12:20So let me just show you what this is all about. So before we actually do anything with the code, let's go here, and we just go to our indentation block. What I'm going to do is use my three quotation marks. That's how we can use a docstring. We'll do 1, 2, 3, and VS code automatically adds another 3 to close off. And anything within these three quotation marks is going to be treated as a docstring. And basically, we just want to describe what this function does. So we can say this function takes two arguments. First, pass in a username.

12:53Second, pass in your email provider. And then we could just say, e.g, Gmail, Outlook, et cetera. So that means anyone reading this code has got a rough idea of what you intend to do. Now, our code, or rather our function here, is pretty simplistic. You can probably infer just by looking at it. But with code, which is more complex, then these docstrings can be really invaluable. Now here's the thing, remember when we used the help function earlier on within this skill? Ultimately, what the help function is going to do is show us what that docstring is.

13:24So as opposed to calling this create_email function, let's pass that into the help function. We'll say help(create_email). OK. So let's save this and see what happens here if we run this script just by using the help function with our newly created custom create_email function. So let's arrow up, hit enter, and look at this. It's showing us our docstring that we created within our triple quotation marks. This function takes two arguments. First, pass in the username. Second, pass in your email provider, e.g. Gmail, Outlook, et cetera.

13:56That is exactly what we wrote within our docstring, and that is, in essence, what the help function does. It pulls the docstring. Now just for variety, well, I'll show you how you can also access this in another way, which some people do. You can just pass this to the print function and then give the name. And I can say doc_ _. This is, in essence, the same thing. Some people prefer to do this method. I personally just like to use the help function. But if you save this, this again is going to give us the exact same information about our function. So we'll say Python3 example3.py, hit enter.

14:28And again, this prints out our docstring. Now the difference here is that this just prints this straight to the terminal, whereas using the help function actually takes you into something called layers, which gives you paging, which I tend to find as pretty handy if we happen to have a really long docstring. We can just keep hitting the space bar and running through the different pages, whereas the print function is just going to splatter it all onto the terminal right here. So you have these two options. But really, the thing to remember-- to take away, is that when they are creating functions, we are going to be using this def keywords.

14:59You specify the name of the function we want to be using lowercase and split our words using underscores. That's a strong Python convention. And then use parentheses. These can take arguments if you want to supply them, and the case if we want to take in particular variables and work with those variables. But as we saw in our earlier function, that is not a necessity. That is just a choice. Then again, we're going to use a colon and then within, again the strong convention has four spaces in, we're going to write our code as the indented block. And within that code is going to be contained within this my function.

15:31And again, just remember to make good use of those triple quotation marks, those docstrings. That is going to really help with the readability and shareability of your code with your functions and make it much easier for your team to understand what exactly is your intent when creating this function. How do we actually use it? Just like we did when we were exploring our built-in functions. OK. So that's how we can create custom function within Python. I hope this has been informative for you, and I'd like to thank you for viewing.

Passing Arguments

0:00[CBT NUGGETS JINGLE] Hey guys, and welcome back. So let's talk more about those arguments that we're passing in to our functions. Now, there are three types of arguments we can pass, and the first is going to be what is called a positional argument, and that is the most common way to assign arguments to parameters within your functions.

0:31Basically, it corresponds to the arguments that we pass in are matched positionally to the parameters that the function accept. And what we also have are default argument. With your default arguments, you can have arguments be made optional by specifying a default value. If you happen to supply a value, then that will overwrite the default. But if you don't happen to supply anything, then the default value will be used. Now, the third type is called a keyword argument.

1:01The keyword argument doesn't care about the order in which you pass in your arguments. You're going to map the arguments explicitly using key words. What does that actually look like? Well, we'll get to see an example of that in this Nugget right here. But for now, let's just recap and see what these look like in action within VSCodes. OK, so let's go and create an example here, OK? So we'll say touch example4.py. And let's go in and open this. We'll say example4.py. OK, so again, let's keep this on the simple side by just using a print statement.

1:34What we'll do here is we'll pretend we're going to gather information about a particular device that we're going to be logging into. Let's just create a function called connection_details,. So let's just say this function is going to set the parameter username. It's going to accept a hostname for the device, and we'll also specify a platform for that device. Not the most realistic example, but don't worry about that just now. So again, we're just going to print this out so we can see what's happening. But let's just say what we want to do is say ssh, followed by the username the person passes in.

2:07So we'll use an if string here. So we'll say ssh username at whatever the hostname is that they pass in. And if the platform that they pass in is equal to the value cisco, once we've done that connection, we want to automatically say enable followed by a new line, and then configure terminal, which is a Cisco command, and we'll do a new line. This is not actually creating a real connection. This is just printing out some text. It's just to give you an idea of how we may work with arguments within our functions.

2:38OK, so let's say I wanted to use this-- in fact, let me just change the name of this function to something a little bit more descriptive. We'll just call this device_login function, OK? It's a little bit more descriptive. So if we want to log in to the device, we can just say device_login. Now, what we're going to use here is positional arguments. OK, so the first parameter is the username, so that will be the first argument we supply. The second position is the hostname parameter, so that's going to be the second argument we supply. And then at the end, we have our platform, which is going to be the third parameter.

3:11So that will be the third argument we supply. OK, so what we'll do here is we'll pass in the username John. That's the first argument, so that's going to map to username based on its position. Then we're going to specify the hostname, and we'll just make this an IP address of 192.168.1.1. Let's just say that's the address of the device. And it's a Cisco device. So those are the three arguments we've passed to this function. So if we just save this, and we'll run this script here, example 4, python3 example 4-- oop, [INAUDIBLE] example4.py, hit Enter.

3:45And basically, we're simulating a login here, [INAUDIBLE] ssh with our username, with the IP address. And because it's a Cisco device, we've automatically done enable to go to privileged EXEC mode and then done configure terminal to go to global configuration modes. So that was based on positional arguments. Here's the thing. If we scroll on down, what about we have some default values? So the way we can specify default values is actually within our function. So what I can say here is let's just assume by default, unless someone supplies a value for a platform, we're going to assume the default value is Cisco, OK?

4:21And then when we do that, is as you see here, we just have an equal sign next to that parameter, and then we correspond that or rather correlate that to a particular value, a default value-- in this case, Cisco. So let's save this now, and what I can do here is I can actually remove this last argument, because effectively, we've supplied argument one, which is going to map to the username based on its position. We've supplied the second argument, which is going to map to the hostname based on its position. And we don't actually have a value for the third argument, but this function does have a default value, so if we don't actually explicitly assign that third value, then it's going to be platform is equal to Cisco.

5:01So again, let's just supply two arguments this time, and rely on that default value to fill in the third. Let's arrow up, hit Enter, and this still works just OK, even though we only supplied two positional arguments. The third argument was just a default. But again, what we can do is we can override that default by supplying a third argument and its position, but this time we'll just say junos for Juniper devices. And if I save this, this part of the code here is not going to execute. We're just going to login, but we're not going to try to say enable configure terminal, because that's a Cisco command, or rather Cisco commands.

5:36OK, so let's try this again. Hit Enter, and now we're just doing a login. We're not doing configure terminal. That is because the third argument we supplied was junos, and that overwrote the default value of Cisco, and because of that, this condition was not true. Therefore, the indented code here did not execute. OK, so those are our positional arguments, and we've seen here a default argument. And in fact, let's add another condition and we'll just say elif platform is equal to junos, we can just say cli, which takes you into the Junos CLI, and then we'll just say edit, which allows you to edit the configuration.

6:09So this time, let's actually run this again. Let's quit to test this. We're going to override the default value. Hit Enter. Because we've got a Junos device supplied, we're now going to say cli, then edit, as opposed to enable config terminal. OK, so like I said, those were positional arguments, default arguments. Let's see how we can use keyword arguments. So basically, the same type of logic does apply. The only thing is we don't actually care the order in which we supply the arguments, whereas earlier, the order was absolutely vital. The order told us to map John to the username and map this IP address to the hostname, and at the end, this was actually a platform.

6:46If we happen to supply Junos at the start here, if we try to log in with the name Junos as opposed to the name John, because of its position. But let's be more explicit by using what is called keyword arguments. Here's what we're going to do here. We can use the exact same function, so we'll call it by saying device login. This time, though, as opposed to just saying John and relying on its position and an IP address and relying on its position again, what we're going to do is just specify the parameters that the actual function takes-- say, for example, username, hostname, and platform-- and directly map them to our arguments.

7:23And it doesn't matter the order in which we supply them, because it's based on the keyword that's explicit. So what I can do now is just say hostname is equal to, and I'll say the hostname is equal to 192.168.1.1. And I can say the platform, and you can see this is auto-completing with VSCode. So the platform is equal to cisco, and I'll say the username is equal to john. So looking at this, this is completely out of order based on its' position. We've got hostname here, whereas hostname is a second argument. We've got platform here in position two, whereas it's defined here as position three.

7:56And the username I've got in position three, whereas that's actually the first argument here. But again, because of being explicit, the function is not in any doubt. It'll say when we pass this in, map the username to john, map the platform to cisco, and map the hostname to 192.168.1.1. And then we can just fill in all these variables. Username is John, hostname is 192.168, and the platform is going to be Cisco, which this means this condition is going to meet. So it doesn't actually matter the order any more. We're being super explicit now.

8:26So watch this. Even out of order now, we should still get our Cisco CLI because everything should still work. Let's hit Enter, and look at this quite the thing. This is using keyword arguments, so really is much more explicit. Then what we can actually do here is use a mixture of all of these. So what I could say here at the start here is device login, and I can use the position number one, john, without specifying anything, and that's going to automatically map to the username. And then, I could say platform is equal to cisco, and the hostname is equal to 192.

9:00Let's use a different IP address for a bit of change. We'll do all the 8s. So clearly, we actually have a mixture of keyword arguments and positional. Here is our positional argument, position one, which is going to be inferred as the username, but these two have actually been reversed. But check this out-- this should still work quite the thing. So let's save here, and we'll clear the screen. So arrow up, hit Enter, and it works, no problem at all. Now, the caveat here, and this is a big caveat, is that once you start using keyword arguments, you cannot use positional arguments after it.

9:31What do I mean when I say here? Well, let's see this, OK? So I have a positional argument here, so that's fine. But now I specified a keyword argument here, OK? This is a keyword argument. So that means that anything that comes after, if I had lots of arguments here, anything after this point, they all have to be keyword arguments. We can't use positional arguments after we have specified the keyword argument. So let me show you this. So let me start by saying username is equal to john, so it's a keyword argument. Now we can't use positional arguments.

10:01We can't say 8.8.8, and that's going to be as inferred as the hostname, and cisco. This is not going to be allowed, because like I say, the positional arguments came after keyword arguments. We can't do that. So let's arrow up, try again, and look at this, positional argument follows keyword argument is not allowed. What we could do is just get rid of the keyword argument here, and suddenly this becomes fine because this is all positional arguments. But again, if we happen to make this one a keyboard argument by saying hostname is equal to, then this one here is going to get the red squiggly line because a positional argument has came after the keyword argument-- not allowed.

10:37So just be aware we have different ways to pass in arguments to our functions. We have positional arguments, we also have default arguments, which allows you to omit particular arguments and just have default values set and used, and we can also specify keyword arguments, which allows us to jumble up the order in which we supply arguments to a function. We can have a mixture of both, so long as we have positional arguments and then keyword arguments after, but we cannot have positional arguments come after a keyword argument has been defined.

11:09OK, those are some of the details of using arguments with functions. I hope this has been informative for you, and I'd like to thank you for viewing.

The Return Statement

0:00[AUDIO LOGO] Hey, guys, and welcome back. So like I said at the very start of this skill is that a function always returns a value. And by default, that value is going to be none. Now you may be thinking, well we've been doing all these print statements. Is that not returning the value? Are we not getting something back? That's actually a little bit different from what I'm talking about.

0:31So what we're going to do in this Nugget right here is to use the return statement. So what the return key, what it's going to do, is it's going to send back the result of this function as opposed to just printing something out. Ultimately, we want to use the return statement when we want to assign the output of a function to a new variable. What exactly am I talking about here? Well, the best thing to do is to see this in action. So let's check it out. OK. Let's say, touch example5.py. And let's dive right back in.

1:01So let's use a similar example that we saw before. We'll just create a function just called generate_email. And we're going to take a user name as well as a provider. Now to build on the knowledge we want, let's say we want to specify a default value for the provider. Therefore, meaning that if they don't actually specify a provider, they're going to have a provider inferred for them. So the way we can do that, as you know, is an equal sign and then we'll specify the default values. So have a default value of a Gmail address. OK. Coo. So now with our colon, we get out indented block and now we began rating our codes.

1:35So what I'm going to do here is we can see the email is equal to-- so we'll email_addy is equal to. And we can use our f-string. So we'll say username at provider, and we'll just say .com And we'll close off our quotation mark. Now recently, all we've been doing is using print statements. So that's what we'll do first. We'll say print email_addy. So like I said, we can call this by saying generate_email. And we can just gather our username because we have a default value of Gmail. So unless you specify something else, we'll get a Gmail address. We'll say ipvzero and we'll save this.

2:08If we run the script, python3 example5, and hit enter. Now our Gmail account has been generated. So this is printed out, quite the thing. But what if we actually want to do something with this Gmail account that we've created? Like we want to manipulate it further within our program? What we want to do here is not just print out. We want to instead return our email address. So instead of printing it, we'll use this keyword return. And we'll just give the name of the variable here. Now watch what happens. If I save this and I try it this script, the output might surprise you.

2:43We'll hit enter, and it appears like nothing has happened. But something has happened. We returned our variable back to the caller. So what am I talking about here? Well this part here is where we called the function. Now what we can do here is we can actually assign the result of this function call to a variable now. So let's say outside here, we can say, my_email is equal to. And we can make it equal to the function. Because what were effectively saying here is that this variable here, my_email, is equal to the result of this function, whatever it returns.

3:21Now what is this returning. It's returning the email addy variable that we generate here by passing another value. So now what we can do here is after you return it, we can still have the option to print it, but we print it outside here. We'll say, print my_email. And let's save this. So now the process is a little bit different. We are returning it back to the caller, assigning it to a new variable, and then printing that new variable. But because we have access to this new variable, we don't just have the option to print it. We can do other things. So what do I mean when I say we can work with it?

3:53So let me show you. Let me just comment this part out here. And what I'll do here is I'll create a list of names. We'll just say, my_names. And we'll say, Trevor. We'll say Knox. We'll say John. We'll say Simona. And we'll just say Bob. And what I want to do is to generate an email for all of these names and to create a new list. So what I'll say here is my_new_list. Let's call it my_email_list. That's a bit more descriptive. And right now, that is going to be an empty list, because we don't actually have any emails generated. What I'm going to do here is I'm going to look through all the names in the my_names list, Trevor, Knox, John, Simona and Bob.

4:29So I'll say for name in my_names names. And if I hit enter, we're going to get an indentation. So what I want to do is for every single name, I want to run the generate_email function. OK. So all I need to do to call that is say generate_email. And I need to pass in a username. And the username is going to be this name variable we're looking through. So I'll just say name here. Now I could just leave it at name, because as we know we have a default value for provider which would give everyone a Gmail address.

4:59But because we all work for CBT Nuggets, let's just say CBT Nuggets will be our provider. So what we're doing here is for every name within this list, we're going to take out that name. And we're going to pass that name into our generate_email function, which is up here. So that becomes the username each time. And we'll specify the provider of CBT Nuggets. So everyone should have their first name here, i.e., trevor@cbtnuggets.com, knox@cbtnuggets.com, so on and so forth. But remember, we're actually returning the email address, which means that we can assign this to a new variable, assign the result of this function to in new variable.

5:37So let's do that just now. And we'll just say, new_email is equal to. So like I said, we have this empty list right here, my_email_list. And all we're going to do here is say, my_email_list, and we'll use the append method. And we'll append the new email that we are generating based on this variable that we can now assign the result of this function to, because that's how the return key works. So now at the end of all this, we should actually have a Python list with all of our emails. So what we can do here is move out our indentation level.

6:08And we'll just print out my_email_list. So if I save this, and say example5.py, and hit Enter. And look at this. We have a Python list with all of our usernames appended to this email. And that's because we got the actual result of our function returned back to us. We could assign it to a variable and then work with it, i.e. we can append it into this list. And if we wanted, what we could do is we could actually unwrap that, and say for email in my_email_list. And then we can do a print statement and say f-string, new email accounts generated.

6:43And then just pass in the email which we are looking through. Save here, clear the screen, and hit Enter. And there we go. So clearly here even though the print statement and the return statement may seem like they have similar functionality, the key here is that the return statement allows us to assign the output of a function to a new variable. This is going to be very useful when we actually want to work with the results of what we get from a function. Okie dokes, so I hope this has been informative for you. And I'd like to thank you for viewing.

Frequently asked questions

What does the Understand Functions in Python lesson cover for network engineers?

The learner on your team defines functions with the def keyword using lowercase, underscore-separated names, then documents them with docstrings and explores built-in functions like print() with help(). The lesson also compares positional, default, and keyword arguments using a device configuration function, and covers return statements that generate values such as an email address.

How long is the Python functions lesson and where does it fit in the Python for Network Engineers course?

The lesson runs 54 minutes inside a course that represents about 22 hours per learner. The course starts with Python fundamentals and data structures, then moves through functions, text files, network automation libraries, Jinja templates, REST APIs, spreadsheets, troubleshooting, testing, and concurrent connections.

Who is the Python for Network Engineers course designed for?

IT Directors can assign it to network administrators with 1 to 3 years of networking experience but little or no Python background who need a practical path into automation. Team Leads can use it as a baseline before asking staff to contribute automation scripts in production environments.

What is the difference between positional, default, and keyword arguments in a Python function?

With positional arguments the order you pass values is vital, while a default argument uses an equal sign in the function definition, such as assuming the platform is Cisco unless another value is supplied. Keyword arguments map each value to a named parameter, so platform, hostname, and username can be passed in any order, and the lesson shows these approaches can be mixed.

How do you view a Python function's docstring?

You can pass the function to help() or print the function's __doc__ attribute. Printing sends the docstring straight to the terminal, while help() opens it in a pager, which is handy for long docstrings.

How can a Training Manager track team progress through this Python course?

Team reporting provides per-learner progress and completion, cohort and group views, and completion exports for audit evidence. Training Managers can also use Playlists to sequence this course with related automation training.

What's next?

Ready to keep going?

For your team

Bring this training to your team

See how CBT Nuggets helps IT teams close skills gaps, hit compliance targets, and prove training ROI.

Book a Demo
Just need Python Functions?

Learning on your own? Browse individual plans ($49/month, billed annually) →

Not ready to buy?
with no purchase required. Already have an account?
Book a Demo