Functions Flashcards
Function
In Python, a function is a named sequence of statements that belong together
Form of function
def name(parameters): statements
Parameter
In the function definition, the parameter list is known as the formal
parameters.
• This list of parameters describes the values that the function will need to
receive from the caller of the function.
• When you call a function, you must provide values to the formal parameters.
• These values are often called as arguments or actual parameters
example of function def
import turtle
# Function definition def draw_square(t, sz): """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90)
# Main program wn = turtle.Screen() wn.bgcolor("lightgreen") alex = turtle.Turtle()
# Call the function to draw the square with actual values for parameter turtle and side draw_square(alex, 50)
wn.exitonclick()
docstrings
formal parameters
arguments (actual parameters)
repeat function as many as we want
import turtle
Function definition
def draw_square(t, sz):
“"”Make turtle t draw a multi-colour square of sz.”””
for i in [‘red’, ‘purple’, ‘hotpink’, ‘blue’]:
t.color(i)
t.forward(sz)
t.left(90)
# Main program wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen")
alex = turtle.Turtle() # create tess and set some attributes
alex.pensize(3)
size = 20 # size of the smallest square
for i in range(15):
draw_square(alex, size)
size = size + 10 # increase the size for next time
alex.forward(10) # move tess along a little
alex.right(18) # and give her some extra turn
wn.exitonclick()
Fruitfull function
A function that return a value is a fruitful function
Example of fruitfull function
# Function definition def square(x): """ Calculate and return x2.""" y = x * x return y
# Main program to_square = 10 result = square(to_square) # need a variable to store the returned value print "The result of ", to_square, " squared is ", result
Global and local variables
Variables and parameters in a function are local, i.e. they only exist inside
the function and you can’t use them outside the function.
It is not possible for a function to set a local variable to a value, complete its
execution, and then when it is called again next time, recover the local
variable.
• Each call of the function creates new local variables, and their lifetimes
expire when the function returns to the caller.
Bad form
# Function definition def bad_square(x): y = x ** power # bad form, DO NOT access global variable return y
# Main program power = 2 result = bad_square(10) print result
functional decomposition.
• It is important to understand that each of the functions we write can be used
and called from other functions we write.
• This is one of the most important ways that allow us to take a large problem
and break it down into a group of smaller problems.