Reviewing Python Functions
00:00 Let’s begin by reviewing what a Python function is.
00:05 Just about every programming language supports user-written functions. Depending on the language, they could be called subroutines, methods, subprograms, procedures, and of course, functions. Some languages make a distinction between procedures and functions, the difference being that functions return a value and procedures don’t.
00:27 In Python, they’re called functions. A function is a self-contained block of code that encapsulates a specific task or related group of tasks. In Python, all functions return a value, whether you indicate so or not.
00:43 You’ll also hear the term method described in Python. A method can be thought of as a function associated with a class or object. Here’s what a function definition looks like.
It begins with the keyword
def. This is a Python reserved word to indicate that what follows is a function definition. Next is the actual name of the function.
01:09 This can be any valid Python identifier, and it’s best to use a name that indicates the purpose of the function. That’s followed by a pair of parentheses, which would include a comma-separated list of parameter names, if any, that the function was going to use. By the way, the angle and square brackets are just placeholders here.
01:30 You wouldn’t actually type them in your function definitions. But you would type the parentheses, even if they were supposed to be empty. A colon is used to indicate the end of the function header.
01:45 What then follows are the Python instructions needed for your function to perform its task. This is referred to as the body of the function, and it is always indented under the function header.
01:59 When you want to use a function, you type the function name and then, inside a set of parentheses, you provide argument values for each of the parameters. And again, even if there are no parameters, you still need parentheses.
02:12 They would just be empty. Nothing would be in between them.
The tutorial uses this notation for modeling a function definition and a function call. Again, you can see the keyword
def, followed by a function name, and then parameter variables in parentheses, then the body of the function indented below the header.
02:35 And a function call where you can see argument values being provided.
Next, we’ll specifically look at the
Become a Member to join the conversation.