Functions are reusable pieces of programs. They allow you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function. We have already used many built-in functions such as len and range.
The function concept is probably the most important building block of any non-trivial software (in any programming language), so we will explore various aspects of functions in this chapter.
Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function. An example will show that this is actually very simple:
#!/usr/bin/python # Filename: function1.py def sayHello(): print('Hello World!') # block belonging to the function # End of function sayHello() # call the function sayHello() # call the function again
$ python function1.py Hello World! Hello World!
How It Works:
We define a function called sayHello using the syntax as explained above. This function takes no parameters and hence there are no variables declared in the parentheses. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results.
Notice that we can call the same function twice which means we do not have to write the same code again.