Are you interested in learning Python? Art, a Python instructor at Noble Desktop, provides a detailed tutorial on how to compose your own Python function.
Key Insights
- In Python, a function is a block of reusable code that can be used repeatedly.
- The creation of a function begins with the keyword 'def', which stands for 'define', followed by the name of the function. The name should reflect the function's purpose.
- Functions can take arguments, which can be defined within the function, as demonstrated by Art with 'a' as 6 and 'b' as 7.
- Instead of printing the result of a function, the 'return' operator is used as a function always returns something.
- To invoke a function, you need to call it by using the function name.
- To save the result of a function, assign it to a variable. These variables can then hold the result from the function.
In this video, we're going to look at how to compose your own function in Python
Video Transcription
Hi, my name is Art and I teach Python at Noble Desktop. Today I'm going to show you how to compose your own function.
A function is a block of reusable code, something we can use over and over again. Let's create our first function.
Start with the keyword 'def', which stands for 'define', and then come up with a name for the function. The name should reflect the purpose of the function, so I'm going to call mine 'add'. This function takes two arguments (a and b). I want to define a as 6 and b as 7. Then I want to do a total of a plus b.
Now we usually print stuff, as humans we want to see what's going on. But in this case, we will use the 'return' operator, because a function always returns something. So I'm going to 'return' total.
Now I have this function, but nothing is going on because I need to call it to invoke the function. So I'm going to use the function name 'add'. You see I'm calling this function and I'm getting the result.
Keep in mind that 'return' should be the last statement within the function, nothing can be done after 'return'. Also, if I want to save the result of the function, I need to assign it to a variable, like 'variable_one' and 'variable_two'.
Now, these variables will hold the result from the function.
In my next video, I'll show you how to call a function within a function. See you in my next video!