Functions on Python
In a programming language, functions are blocks of code that accomplish tasks. When using functions, you must use the proper syntax and supply the correct number and type of arguments to avoid errors. Almost any Python program you write will make use of at least one function, whether it's a built-in function or one you write yourself.
-
Purpose
-
Functions are reusable code that provide modularity to a program. In many cases, you need to use the same block of code repeatedly in one program, for example, the buttons on a calculator. Instead of writing the code to do it several times, you can write a function once and then call it as many times as you need to. Generally, functions only perform one task or calculation such as comparing two strings or adding numbers together.
Arguments
-
A Python function can accept several kinds of arguments, including literal values, variables, lists and tuples. In functions that accept more than one argument, separate each using a comma. When you use or modify these values in the function, their original values outside the block of code remain unchanged. Some functions have a required number of arguments. You must supply these values in the correct data types or else Python returns an object type error.
-
Calling a Function
-
The process to call function in Python works the same as it does in most other popular programming languages. Type the function name, followed by the list of arguments in brackets, if necessary. For example, type "len('My string')" to call the length function to count the number of characters in the parameter; in this case, nine. You can save values returned by functions into variables for use elsewhere in your program. For example, type "var = len('My string')" to do this.
User-Defined Functions
-
You make your own functions in Python by typing the keyword "def" followed by the name of the function and list of parameters in brackets and then a semi-colon. For example, typing "def myfunc( var1, var2):" defines a new function. The following lines define the body of the function up until a blank line, which signifies the end of the function's block of code. You can create new functions and call them from anywhere in your program's code.
-