Defining Functions
Functions must be defined, to create and use
certain functionality. There are many built-in functions that comes with the
language python (for instance, the print() function), but you can also define
your own function. When defining functions there are multiple things that need
to be noted;
Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
def <function_name ([parameter1, parameter2…]
)> :
<Block of Statements>
return <expression / None>
Block:
A block is one
or more lines of code, grouped
together so that they are treated as
one big sequence of statements while execution. In Python, statements in a
block are written with indentation.
Usually, a block begins when a line
is indented (by four spaces) and all the statements of the block should be at
same indent level.
·
Any input parameters or arguments should be placed within these
parentheses when you define a function.
·
The code block always comes after a colon (:) and is indented.
·
The statement “return
[expression]” exits a function, optionally passing back an expression to
the caller. A “return” with no
arguments is the same as return None.
Note
Python keywords should not be used as function
name.
Note
In the above Syntax, the Text which is given in
square bracket [] is optional.
A block within a block is called nested block.
When the first block statement is indented by a single tab space, the second
block of statement is indented by double tab spaces.
Here is an example of defining a function;
Do_Something( ):
value =1 #Assignment Statement
return value #Return Statement
Now let’s check out functions in action so you
can visually see how they work within a program. Here is an example for a
simple function to display the given string.
Example:
def hello():
print (“hello - Python”)
return
1. Functions help us to divide a program into
modules. This makes the code easier to manage.
2. It implements code reuse. Every time you
need to execute a sequence of statements, all you need to do is to call the
function.
3. Functions, allows us to change functionality
easily, and different programmers can work on different functions.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.