0% found this document useful (0 votes)
4 views5 pages

Lesson06 Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Lesson06 Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Lesson 6: Functions

A function is a block of organized, reusable code that is used to perform a


single, related action. Python has many built-in functions like print(), etc.

In addition to the built-in functions, user-defined functions can also be created.

Function Definition
 Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these
parentheses.
 Parameters can also be defined inside these parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and is
indented.
 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.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and should be passed in the
same order that they were defined.
Example

def calc_area( radius ):


area=3.142*radius*radius
print (area)
return
Calling a Function
Defining a function gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Example

calc_area (7)
Pass by Reference vs Value

A. Irungu
Python utilizes a system, which is known as “Call by Object Reference” or “Call
by assignment”.
Whenever arguments of immutable objects like whole numbers, strings, or
tuples are passed as arguments to a function, the passing is like call-by-value
because their value cannot be changed.
On the other hand, passing of mutable objects like lists, can be considered as
call by reference because their values can be changed inside the function.
Example1: Call by value

def calc_area( radius ):


area=3.142*radius*radius
print ("The area is " + str(area))
radius*=2
return
r=float(input("Enter the radius of a circle : "))
print (r)
calc_area (r)
print (r)

Example1: Call by Reference

def calc_volume( args):


vol=3.142* args [0]* args [0]* args[1]
print ("The volume is " + str(vol) + " cubed")
args[0]*=2
return
dimensions=[7,10]
print(dimensions) # before the function call
calc_volume (dimensions) # first call to the function
print(dimensions) # after the function call

Function Arguments
A function call can be made using the following types of formal arguments-
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required Arguments

Required arguments are the arguments passed to a function in correct


positional order. In this case, the number of arguments in the function call
should match exactly with the function definition.
To call the function calc_volume you must pass two arguments, otherwise a
syntax error will occur.
Example:

A. Irungu
def calc_volume(radius, height):
vol=3.142* radius*radius *height
print ("The volume is " + str(vol) + " cubed")
return
calc_volume (7, 10) # function call using required arguments

Keyword Arguments

When keyword arguments are used in a function call, the caller identifies the
arguments by the parameter name. This allows skipping or placing arguments
out of order because the Python interpreter can use the keywords provided to
match the values with parameters.
Example:
calc_volume (height=10, radius=7) # function call using keyword arguments

Default Arguments

A default argument is an argument that assumes a default value if a value is


not provided in the function call for that argument.

Example:

def calc_volume(radius, height=10):


vol=3.142* radius*radius *height
print ("The volume is " + str(vol) + " cubed")
return
calc_volume (7) # function call using default arguments
calc_volume (7,14) # function call without using default arguments

Variable-length Arguments

Variable-length arguments are used when there is need to process more


arguments than those specified during function definition. Variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
An asterisk (*) is placed before the variable name that holds the values of all
non-keyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call.
def calc_volume(r, *varHeight):
for height in varHeight:
print ("The volume is " + str(3.142* r* r *height) + " cubed")
return
calc_volume(7,10,20,30,40)

A. Irungu
Anonymous Functions
Anonymous functions are not defined in the standard manner; using the def
keyword. The lambda keyword is use do create small anonymous functions.
 Lambda functions can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression.
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
 Although it appears that lambdas are a one-line version of a function,
they are not equivalent to inline functions in C or C++, whose purpose is
to stack allocation by passing function, during invocation for performance
reasons.
Syntax

lambda [arg1 [, arg2, ..., argn]]: expression

Example

vol = lambda radius, height: 3.142*radius**2*height # Function definition


in one line
print ("Volume is: ", vol (10, 2)) # a function call

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.
Example

def calc_volume(r, h):


vol=3.142* r**2*h
return vol
print ("The volume is " + str(calc_volume (10,2)) + " cubed")

Scope of Variables

The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in
Python-

 Global variables
 Local variables

A. Irungu
Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope. 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.

Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a


dictionary of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the


global namespace. If a local and a global variable have the same name, the
local variable shadows the global variable.

Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions. Python takes any variable assigned a value
in a function is local. Therefore, in order to assign a value to a global variable
within a function, the global statement must be used. The statement global
VarName tells Python that VarName is a global variable. In which case, python
won’t search the local namespace for the variable.

A. Irungu

You might also like