Python Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:
● create a circle function
● create a color function
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
There are two types of function in Python programming:
● Standard library functions - These are built-in functions in Python that
are available to use.
● User-defined functions - We can create our own functions based on our
requirements.
Python Function Declaration
The syntax to declare a function is:
def function_name(arguments):
# function body
return
Here,
● def - keyword used to declare a function
● function_name - any name given to the function
● arguments - any value passed to function
● return (optional) - returns value from a function
Let's see an example,
def greet():
print('Hello World!')
Here, we have created a function named greet(). It simply prints the text
Hello World!.
This function doesn't have any arguments and doesn't return any values. We
will learn about arguments and return statements later in this tutorial.
Calling a Function in Python
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
Now, to use this function, we need to call it.
Here's how we can call the greet() function in Python.
# call the function
greet()
Example: Python Function
def greet():
print('Hello World!')
# call the function
greet()
print('Outside function')
Output
Hello World!
Outside function
In the above example, we have created a function named greet(). Here's how
the program works:
Working of Python Function
Here,
● When the function is called, the control of the program goes to the
function definition.
● All codes inside the function are executed.
● The control of the program jumps to the next statement after the
function call.
Python Function Arguments
As mentioned earlier, a function can also have arguments. An argument is a
value that is accepted by a function. For example,
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function with no argument
def add_numbers():
# code
If we create a function with arguments, we need to pass the corresponding
values while calling them. For example,
# function call with two values
add_numbers(5, 4)
# function call with no value
add_numbers()
Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get values
5 and 4 respectively.
Example 1: Python Function Arguments
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
# function call with two values
add_numbers(5, 4)
# Output: Sum: 9
In the above example, we have created a function named add_numbers() with
arguments: num1 and num2.
The return Statement in Python
A Python function may or may not return a value. If we want our function to
return some value to a function call, we use the return statement. For
example,
def add_numbers():
...
return sum
Here, we are returning the variable sum to the function call.
Note: The return statement also denotes that the function has ended. Any
code after return is not executed.
Example 2: Function return Type
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)
# Output: Square: 9
In the above example, we have created a function named find_square(). The
function accepts a number and returns the square of the number.
Working of functions in Python
Example 3: Add Two Numbers
# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
# calling function with two values
result = add_numbers(5, 4)
print('Sum: ', result)
# Output: Sum: 9
Python Library Functions
In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,
● print() - prints the string inside the quotation marks
● sqrt() - returns the square root of a number
● pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we
must include the module inside our program.
For example, sqrt() is defined inside the math module.
Example 4: Python Library Function
import math
# sqrt computes the square root
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
# pow() comptes the power
power = pow(2, 3)
print("2 to the power 3 is",power)
Output
Square Root of 4 is 2.0
2 to the power 3 is 8
In the above example, we have used
● math.sqrt(4) - to compute the square root of 4
● pow(2, 3) - computes the power of a number i.e. 23
Here, notice the statement,
import math
Since sqrt() is defined inside the math module, we need to include it in our
program.
Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in our
program which makes our code reusable. For example,
# function definition
def get_square(num):
return num * num
for i in [1,2,3]:
# function call
result = get_square(i)
print('Square of',i, '=',result)
Output
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
In the above example, we have created the function named get_square() to
calculate the square of a number. Here, the function is used to calculate the
square of numbers from 1 to 3.
Hence, the same method is used again and again.
2. Code Readability - Functions help us break our code into chunks to make
our program readable and easy to understand.
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem,
assuming that no worth is provided for the contention when the capability is called. The
following example demonstrates default arguments.
Code
1. # Python code to demonstrate the use of default arguments
2. # defining a function
3. def function( n1, n2 = 20 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7.
8. # Calling the function and passing only one argument
9. print( "Passing only one argument" )
10. function(30)
11.
12. # Now giving two arguments to the function
13. print( "Passing two arguments" )
14. function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning
a capability with watchword contentions, the client might tell whose boundary esteem it
is by looking at the boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the
Python translator will interface the furnished watchwords to connect the qualities with
its boundaries. One more method for utilizing watchwords to summon the capability()
strategy is as per the following:
Code
1. # Python code to demonstrate the use of keyword arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined
positional sequence. The number of arguments required in the method call must be the
same as those provided in the function's definition.
We should send two contentions to the capability() all put together; it will return a
language structure blunder, as seen beneath.
Code
1. # Python code to demonstrate the use of default arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be
20 and num2 to be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )
Output:
Passing out of order arguments
number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions.
However, we need a capability. This can be accomplished with one of two types of
characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
1. # Python code to demonstrate the use of variable-length arguments
2. # Defining a function
3. def function( *args_list ):
4. ans = []
5. for l in args_list:
6. ans.append( l.upper() )
7. return ans
8. # Passing args arguments
9. object = function('Python', 'Functions', 'tutorial')
10. print( object )
11.
12. # defining a function
13. def function( **kargs_list ):
14. ans = []
15. for key, value in kargs_list.items():
16. ans.append([key, value])
17. return ans
18. # Paasing kwargs arguments
19. object = function(First = "Python", Second = "Functions", Third = "Tutorial")
20. print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
return Statement
When a defined function is called, a return statement is written to exit the function and
return the calculated value.
Syntax:
1. return < expression to be returned as output >
The return statement can be an argument, a statement, or a value, and it is provided as
output when a particular job or function is finished. A declared function will return an
empty string if no return statement is written.
A return statement in Python functions is depicted in the following example.
Code
1. # Python code to demonstrate the use of return statements
2. # Defining a function with return statement
3. def square( num ):
4. return num**2
5.
6. # Calling function and passing arguments.
7. print( "With return statement" )
8. print( square( 52 ) )
9.
10. # Defining a function without return statement
11. def square( num ):
12. num**2
13.
14. # Calling function and passing arguments.
15. print( "Without return statement" )
16. print( square( 52 ) )
Output:
With return statement
2704
Without return statement
None
Python Recursion
Recursion is the process of defining something in terms of itself.
In Python, we know that a function can call other functions. It is even possible
for the function to call itself. These types of construct are termed as recursive
functions.
The following image shows the working of a recursive function called recurse.
Following is an example of a recursive function to find the factorial of an
integer.
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
3. Recursive functions are hard to debug.