Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Functions in Python

Naming in General
■ Subroutines, subprograms, functions,
procedures and methods are all
basically the same thing
■ Subroutine and subprogram are
usually more general, with functions
returning values and procedures
producing side effects
■ Methods are functions or procedures
belonging to a class of objects like
the .format on strings.
Subprograms

■ Make large programs easier to write,


read, debug
■ Must be declared before they can be
used or called
■ Can have parameters passed to them
– act as input to be operated on
Functions

■ In python, subprograms are called


functions regardless of whether they
return something or not
■ Methods are still a thing in python and
require an instance of a class to be run
(more on this later). Methods are
functions belonging to an object.
Example: function declaration
Parameters being passed to it: names
Name of Function of variables separated by commas

Value returned

End of the function


Here we call the
Produces the output: function
Functions can return no values
Parameters being passed to it: names
Name of Procedure only, types are figured out

no “result”
Procedure is called twice

Produces the output:


Reference Parameters

● All parameters in python are passed by value, but all


names (variables) are references. This means that
your parameters are copied references. If dealing
with object, you can manipulate them, but if you try to
reassign a parameter to a new value it will not affect
the value of the parameter for the caller.
Example of Reference
Parameters
Produces the Output:

If you use parametersname=something, you effectively break


the link of your parametersname to the calling parameter and
assign it a new variable (which doesn't propagate back).
Global variables are declared outside
subprograms. Functions can change them even if
they are not parameters

Produces the Output:

You might also like