Python Function With Advanced Examples

This article entitle Python Function is a continuation of the previous article entitled Python Date Time.

A function is a block of reusable and organized code that performs a specific task in a program.

What is a Python function?

In Python, the function is a block of code that will only run when it is called into another class.

Further, Python functions will return a value with the use of a return statement once it was specified. This function will be called anywhere once the function will be stated.

Syntax

def nameOfFunction( parameters ):
   "function_docstring"
    function_suite
    return [expression]

The following are the simple rules that define a Python function.

  • A function begins with the def keyword followed by a name of the function and parenthesis( () ).
  • Any kind of input arguments or parameters should be put inside the parenthesis and you can define also the parameters inside the parenthesis.
  • The first function of the statement could be an optional statement and the docstring or a function documentation string.
  • The block of code within each function should start with a colon (:) and be indented.
  • The return statement or expression will exit a function and freely pass back the expression to the caller. The return statement without an argument is similar to a return none value.

Example

def name( str ):
   "This prints a passed string into this function"
   print (str)
   return

How to call the function in Python?

The function should have a name and the parameters should be specified to include in the functions and the structure code blocks.

Once the structure of the function is already finalized, you can now execute the function by calling it from another member of the function or directly from the Python class.

Example

# Function definition is here
def name( str ):
   "This prints a passed string into this function"
   print (str)
   return;

# Now you can call name function
name("First sample name Glenn Magada Azuelo")
name("Second sample name Angel Jude Suarez")

Output

First sample name Glenn Magada Azuelo
Second sample name Angel Jude Suarez

Passing by reference vs value in Python

All the arguments or (parameters) in Python were passed by the reference which means if you want to change the parameters that refer to within the function, it will also reflect the changes in the function that is called.

Example

# Function definition is here
def numbers( numberList ):
   "This changes a passed list into this function"
   numberList.append([2,4,6,8]);
   print ("Values inside the function: ", numberList)
   return

# Now you can call number function
numberList = [20,30,40];
numbers( numberList );
print ("Values outside the function: ", numberList)

Output

Values inside the function:  [20, 30, 40, [2, 4, 6, 8]]
Values outside the function:  [20, 30, 40, [2, 4, 6, 8]]

There is another example where the argument is passed by the reference and the other reference will be overwritten inside the function that is called.

Example

# Function definition is here
def numbers( numberList ):
   "This changes a passed list into this function"
   numberList = [2,4,6,8]; # This would assig new reference in mylist
   print ("Values inside the function: ", numberList)
   return

# Now you can call changeme function
numberList = [20,30,40];
numbers( numberList );
print ("Values outside the function: ", numberList)

Output

Values inside the function:  [2, 4, 6, 8]
Values outside the function:  [20, 30, 40]

Python Function Arguments

You can simply call the function with the use of the following function arguments.

  • Keyword arguments
  • Default arguments
  • Required arguments
  • Variable-length arguments

Keyword arguments in Python

The keyword arguments are associated with the call function once you use the keyword arguments in a call function, the caller will identify the arguments by a parameter name.

Further, it allows us to skip the arguments or place them out of order for the reason of the Python interpreter will be able to use the keywords provided to match all the values within the parameters.

Example

# Function definition is here
def name( str ):
   "This prints a passed string into this function"
   print (str)
   return;

# Now you can call printme function
name( str = "True Heroes will use sourcecodehero")

Output

True Heroes will use sourcecodehero

The example below will provide a more detailed program. Just always keep in mind that the order of parameters could not matter.

Example

# Function definition is here
def info( name, position ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Poition: ", position)
   return;

# Now you can call info function
info( position="Programmer", name="Glenn" )

Output

Name:  Glenn
Poition:  Programmer

Default Arguments in Python

The default argument is an argument in Python that assumes the default value if the value provided is not in the call function on that argument.

Example

# Function definition is here
def info( name, position = "Programmer" ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Position ", position)
   return;

# Now you can call printinfo function
info( position="Programmer", name="Glenn" )
info( name="Glenn" )

Output

Name:  Glenn
Position  Programmer
Name:  Glenn
Position  Programmer

Required Arguments in Python

The required arguments are arguments in Python that are passed to the function in the correct positional order. Further, the number of arguments in the call function could match exactly the definition of the function.

Example

# Function definition is here
def name( str ):
   "This prints a passed string into this function"
   print (str)
   return;

# Now you can call name function
name()

Output

Traceback (most recent call last):
  File "<string>", line 8, in <module>
TypeError: name() missing 1 required positional argument: 'str'

Variable-length arguments in Python

For instance that you need to process the function for multiple arguments more than you specified while setting up the function this argument is called a variable length and not named in the definition of the function unlike the default and required arguments.

Syntax

def nameOfFunction([formal_args,] *var_args_tuple ):
   "function_docstring"
    function_suite
    return [expression]

The asterisk (*) will be placed before the name of the variable that holds the value of all the non-keyword arguments. This tuple will remain empty if there are no additional arguments that are specified during the call function.

Example

# Function definition is here
def info( arg1, *vartuple ):
   "This prints a variable passed arguments"
   print ("Output is: ")
   print (arg1)
   for var in vartuple:
      print (var)
   return;

# Now you can call info function
info( 200 )
info( 700, 600, 500 )

Output

Output is: 
200
Output is: 
700
600
500

Anonymous function in Python

The anonymous function is called anonymous for the reason they are not declared in a standard manner with the use of the def keyword. The keyword lambda can use to create small anonymous functions.

Syntax

lambda [arg1 [,arg2,.....argn]]:expression
  • A lambda is a form that can grasp any number of arguments but can return a single value in the form of an (expression) and cannot contain commands and multiple Python expressions.
  • The anonymous function will not be a direct call to print for the reason of lambda will require an expression.
  • The Lambda functions can only have access to variables in their parameter list and those in the global namespace have their own local namespace in Python.
  • Even though that lambda appears in only a single-line version of the Python function, they were not equivalent to an inline statement in C++ or C, that the purpose is to pass the stack function allocation during the invocation for performance reasons.

Example

# Function definition is here
total = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function
print ("Value of total : ", total( 20, 50 ))
print ("Value of total : ", total( 40, 10 ))

Output

Value of total :  70
Value of total :  50

Scope of variables in Python

All the variables in the Python program will not be accessible in all locations in the program this only depends on where you have declared the variable.

Further, the scope of the variable will determine if the portion of the Python program where you can access the particular identifier

The following are two basic scopes of variables.

  • Local variables – The local variables in Python are variables that are declared within the function. Further, they are defined within the local scope which means that the user can only access a variable inside only of the function.
  • Global variables – A global variable is a function that can access outside or inside of the functions.

Example

total = 100; # This is global variable.

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( 300, 100 );
print ("Outside the function global total : ", total)

Output

Inside the function local total :  400
Outside the function global total :  100

Summary

In summary, you have read about Python Functions. We also discussed in this article what is a Python function, how to call the function, passing by reference vs value, four types of function arguments, an anonymous function, and the scope of variables.

I hope this article could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment