This week, Python 101 discusses how to abstract out parts of yourPython code into reusable functions, add flexibility to them by allowingthem to accept different arguments, and make them return specific values.Also included: a discussion of variable scope and functions to help youwrite your own functions. Confused? All is explained within...
Ask a geek to define the term "function", and he'll probably tell you that a function is "a block of statements that can be grouped together as a named entity." Since this definition raises more questions than answers (the primary one being, what on earth are you doing hanging around with geeks in the first place), I'll simplify that definition a little: a function is simply a set of program statements which perform a specific task, and which can be "called", or executed, from anywhere in your program.
Every programming language comes with its own functions - you'll remember my frequent use of the print(), input() and range() functions from previous articles in this series - and typically also allows developers to define their own functions. For example, if I had a series of numbers, and I wanted to reduce each of them by 20%, I could pull out my calculator and do it manually....or I could write a simple Python function called cheatTheTaxman() and have it do the heavy lifting for me.
There are two important reasons why functions are a Good Thing. First, a user-defined function allows you to separate your code into easily identifiable subsections, thereby making it easier to understand and debug. And second, a function makes your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program.