What are Python Functions?
A function is a collection of related assertions that performs a mathematical, analytical, or evaluative operation. Python functions are simple to define and essential to intermediate-level programming. The exact criteria hold to function names as they do to variable names.
Advantages:
Advantages:
- By including functions, we can prevent repeating the same code block repeatedly in a program.
- Python functions, once defined, can be called many times and from anywhere in a program.
- If our Python program is large, it can be separated into numerous functions which is simple to track.
- The key accomplishment of Python functions is we can return as many outputs as we want with different arguments.
- def name_of_function( parameters ):
- """This is a docstring"""
- # code block
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(9)
print( "The square of the number is: ", object_ )
Output:
The square of the number is: 81
=================================================================
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must be passed to the function, and structuring the code block.
Code:
def a_function( string ):
"This prints the value of length of string"
return len(string)
# Calling the function we defined
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length of the string Python is: 6
=================================================================
Pass by Reference vs. Value
Code:
# defining the function
def square( my_list ):
'''''This function will find the square of items in list'''
squares = []
for l in my_list:
squares.append( l**2 )
return squares
# calling the defined function
list_ = [45, 52, 13];
result = square( list_ )
print( "Squares of the list is: ", result )
Output:
Squares of the list is: [2025, 2704, 169]