You are on page 1of 11

Functions

in Python
Purpose of a Function
• break up code into specific tasks
• make large programs easier to read,
write and debug
• create reusable code
How do Functions Work?
• Block of code which only runs when it is called.
• Must be declared with keyword def before they
can be called (above the code that calls it)
• Can have “parameters”/information passed to
them - used as input to be operated on
• May or may not return a value to the main
program
Built-in Functions we Know
• There are many functions that are built into the Python
language. We don’t see the code for them but we can
use them:
– Ex. print(“Hello.”);
• print function: You send it a parameter “Hello” and it figures
out how to display that on the screen.
– Ex. biggestNum = max(2,5);
• max function: You send it 2 parameters (2, 5) and it sends
you back the larger of the 2 items.
• Some specialized functions are called methods - they
belong to an object.
– Ex. myCircle.draw (win);
• .draw method: is an action that can be performed on a
circle object
Functions that return nothing
• Some functions just do a job, and don’t return
any values to the main program.
• In other languages these may be called
procedures:
Ex. A function that displays a bunny.
Function definition

Function contents
tabbed in

Function call
Functions with Parameters
• Some functions require information
(parameters) to do their job.
• That information can be sent in the brackets.

newGuy and “Bob” are passed as parameters to the greeting function.


The function stores them in a variable called name, and uses name to
do its job.
Functions that return values

● Functions can have any number of parameters, separated by


commas.
● To send a value back, you need a return statement
● If the function is returning a value, it needs somewhere to go!
○ answer = adder(10, 20);
or
○ print("The total is:", adder(10, 20));
Compare these examples:
#No parameters, no return value:
def Simon_says():
print( “ Jump up and down”);

Simon_says();

# Includes parameters and return value:


def Simon_says(this1, this2):
do_this = this1 + this2
return do_this;

action = Simon_says("Up", "Down");


print("Simon said: ", action);
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