Why Use Functions?
00:10 They may be called something different: subroutines, procedures, methods, subprograms, and of course, functions. They’re that useful! But why have them? Well, one reason would be for abstraction and reusability.
01:11 The answer is to define a Python function to perform that task. Every time you need to use it, you simply call it. And if you need to make a change to it, you only need to change the function the one time, and then everywhere where that function is used it will use that new version. Each time you call it, you would provide the argument values needed for each particular call.
01:48 Modularity allows you to take a complex process and break it down into smaller steps. Suppose, for example, you had a program that was going to read data from a file, process that data in some way, and then save that process information back to another file.
02:22 That’s a lot to look at in one particular unit. It’s going to be tough to solve problems in a program doing this many things at once. A better solution would be to take each of these segments and write a function to perform that task. Create a function to just read the data, and whatever steps are there go in that function.
02:48 Create another function to process the data, and whatever instructions were involved there would go in that function. And then another function to save that data back to a file with its related statements.
03:02 Then, your main program looks much cleaner. You simply call each of the functions. Now, this is kind of an abstract example. You might actually need arguments passed and return values saved to actually coordinate what happens from one function to the next, but this is just to give you a look at how much cleaner this program is when we break it down into these steps.
04:10 So, you can always use the best variable name or the best identifier name for an object and don’t have to worry about some other function somewhere else in the program also trying to use that same name.
Become a Member to join the conversation.