A function is a block of code which only runs
when it is called. Python
allows us to divide a large program into the basic building blocks known as
function.
The function contains the set of programming
statements enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the python program.
Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions which can be called user-defined functions.
Advantage
of Functions in Python-
There are the following advantages of Python
functions:
- By using functions, we can avoid rewriting same
logic/code again and again in a program.
- We can call python functions any number of times
in a program and from any place in a program.
- We can track a large python program easily when
it is divided into multiple functions.
- Reusability is the main achievement of python
functions.
- However, Function calling is always overhead in a
python program.
Creating
a function –
In python, we can use def keyword to define the function. The syntax to define a function in python is given below.
def my_function():
function-suite
return <Expression>
Function calling –
In python, a function must be defined before the
function calling otherwise the python interpreter gives an error. Once the
function is defined, we can call it from another function or the python prompt.
To call the function, use the function name followed by the parentheses.
A simple function that prints the message “Hello Word” is given below.
def hello_world():
print("hello world")
hello_world()
output-
hello world
Parameters in function –
The information into the functions can be passed
as the parameters. The parameters are specified in the parentheses. We can give
any number of parameters, but we have to separate them with a comma.
Consider the following example which contains a
function that accepts a string as the parameter and prints it.
Example-
#python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Output-
Enter a: 10
Enter b: 20
Sum = 30
The return Statement –
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
Output-
Inside the function : 30
Outside the function : 30
Types of arguments in the function –
There may be several types of arguments which can be passed at the time of function calling.
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments-
Till now, we have learned about function calling
in python. However, we can provide the arguments at the time of function
calling. As far as the required arguments are concerned, these are the
arguments which are required to be passed at the time of function calling with
the exact match of their positions in the function call and function
definition.
If either of the arguments is not provided in the
function call, or the position of the arguments is changed, then the python
interpreter will show the error.
Consider the following example.
#the argument name is the required argument to the function func
def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))
Output-
Enter the name?John
Hi John
Keyword arguments –
Python allows us to call the function with the keyword arguments. This
kind of function call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the
function calling and definition. If the same match is found, the values of the
arguments are copied in the function definition.
Consider the following example.
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)
func(name = "John",message="hello") #name and message is copied with the values John and hello respectively
Output-
Printing the message with John and hello
Variable length Arguments –
In the large projects, sometimes we may not know
the number of arguments to be passed in advance. In such cases, Python provides
us the flexibility to provide the comma separated values which are internally
treated as tuples at the function call.
However, at the function definition, we have to
define the variable with * (star) as *<variable – name >.
Consider the following example.
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
john
David
smith
nick
Default Arguments –
Python allows
us to initialize the arguments at the function definition. If the value of any
of the argument is not provided at the time of function call, then that
argument can be initialized with the value given in the definition even if the
argument is not specified at the function call.
Example-
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default value of age is considered in the function
Output:
My name is john and age is 22
Scope of variables –
The scopes of the variables depend upon the
location where the variable is being declared. The variable declared in one
part of the program may not be accessible to the other parts.
In python, the variables are defined with the two
types of scopes.
- Global variables
- Local variables
Variables that are defined inside a function body
have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed
only inside the function in which they are declared, whereas global variables
can be accessed throughout the program body by all functions. When you call a
function, the variables declared inside it are brought into scope. Following is
a simple
example –
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
Recursion:
Python also accepts
function recursion, which means a defined function can call itself.
Recursion is a common
mathematical and programming concept. It means that a function calls itself.
This has the benefit of meaning that you can loop through data to reach a
result.
The developer should
be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very
efficient and mathematically-elegant approach to programming.
In this
example, tri_recursion() is a function that we have
defined to call itself (“recurse”). We use the k variable as the
data, which decrements (-1) every time we recurse. The recursion ends when
the condition is not greater than 0 (i.e. when it is 0).
To a new developer it
can take some time to work out how exactly this works, best way to find out is
by testing and modifying it.
Example –
deftri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Output-
Recursion Example Results:
1
3
6
10
15
21
In the next chapter we will go through several function examples
Reference–
W3school
Tutorialpoint
Javapoint