Chapter-3 Functions in Python
Chapter-3 Functions in Python
Chapter-3 Functions in Python
def function_name(arguments):
# function body
return
Here,
def greet():
print('Hello World!')
Output
Hello World!
Outside function
Here,
When the function is called, the control of the program goes to the function
definition.
The control of the program jumps to the next statement after the function call.
Flow of execution in a function call
The flow of execution refers to the order in which statements are executed during
a program run. The program’s opening statement is where execution always
starts. The statements are carried out one at a time, in ascending order. Although
the order in which a programme runs is unaffected by function declarations, keep
in mind that statements inside a function are not performed until the function is
called.
Example –
Defining function
def sum(x, y) :
Calling function
sum(a,b)
3. Keyword arguments – When values are supplied into a function, they are
known as keyword arguments . The assignment operator, =, and a parameter
come before a keyword argument.
Functions in Python may or may not return a value. You already known about it.
There can be broadly two types of functions in python.
a. Function returning some value (non-void functions)
b. Function not returning any value (void functions)
Composition
Example
An arithmetic expression
greater((4+5), (3+4))
A logical expression
test(a or b)
A function call (function composition)
int(str(52))
int(float(―52.5‖)*2)
int(str(52) + str(10))
Scope of Variable
The rules that determine which areas of the programme a specific piece of code
or data item would be known as and be accessible within are known as a
language’s scope rules.
1. Global Scope
2. Local Scope
Global Scope – A name defined in a program’s top-level (_main) segment is
said to have a global scope and be usable throughout the entire programme and
all blocks contained therein.
Local Scope – Local scope describes a name that is declared in the body of a
function. It can only be utilized in this function and the other blocks that are
placed beneath it. The formal arguments’ names also have a local scope.
Type of Function
User-defined functions are the fundamental building block of any programme and
are essential for modularity and code reuse because they allow programmers to
write their own function with function name that the computer can use.
A function definition begins with def (short for define). The syntax for creating a
user defined function is as follows –
Syntax –
The items enclosed in ―[ ]‖ are called parameters and they are optional.
Hence, a function may or may not have parameters. Also, a function may
or may not return a value.
Function header always ends with a colon (:).
Function name should be unique. Rules for naming identifiers also applies
for function naming.
The statements outside the function indentation are not considered as part
of the function.