Functions in Python 3
Function is defined as the named group of statements which can be used to perform a specific task. A function in Python can contain one or more Python statements.
When we call a function, all the statements written within the function body get executed on after another.
Advantages of a function
- It is easy to locate and correct errors in a function.
- Function reduces complexity of a program.
- It is easy to perform testing of a program.
- They are used to divide a bigger problem into smaller sections.
- A function once defined can be used by other functions as well as programs so a programmer can build a new application using existing functions .
- It helps in avoiding repetition of code which saves time and space.
Defining a function in Python
A function must be defined before it can be called within a program.
Syntax of a Function:
The syntax of a function is:
def specifies that a function definition is starting.
Func_name refers to the name of function defined by the programmer. It should follow all the rules of a valid identifier of Python.
Arguments is the set of variables declared within the pair of parenthesis after the function name.
Each of these variables are known as function arguments/parameters. Arguments are used to receive values from another functions.
Local Variables: In this part, we declare local variables of function. These variables are usable only within the function only.
These variables automatically get destroyed when program control leaves the function. Indent must be given before local variables.
Statement-Block: It is set of valid Python statements which would execute when we call the function within another function.
Indent must be given before statements that are part of Statement-Block.
return is used when function returns some value. It appears with an expression within a pair of parenthesis after it.
Indent must be given before return statement.
Expression: It is any valid expression of Python that is to be returned by the function.
|Defining function in Python|
|def message(): |
|def shownumber(num): |
|Two functions namely message() and shownumber() have been defined in above program.|
Calling a Function ( Using a Function )
A function can be called by specifying its name followed by the required number of actual arguments separated by commas enclosed in parenthesis.
If no arguments are required then there must be empty pair of parenthesis after function name.
To call function message() defined above, we can write the following statement
To call function shownumber() defined above, we can write the following statement.
On calling function shownumber(10), value 10 is sent as argument to function. 10 will go and store in argument named num. Value of num is displayed in function body.
|Defining and calling function in Python|
|def message(): |