4. A function is an action performed
by an object. Functions are actions
an object can do. moveRight() is a
function. Function names are
always followed by parentheses.
5. You’ve been using functions already! When you
type hero.cleave(), cleave() is a function. So far
you’ve only been using built-in functions, but you
can also write your own. First, you need to define
the function using def.
6. What is the difference between defining and calling?
(Defining needs def before, and a colon after. Then it has some code indented
under it. They both have parentheses.)
Programmers use functions to make their code easy to read and quick to
write. It’s sort of like a set play in basketball: you know how to shoot, dribble,
and pass, so you can make up a function that combines those parts and give
it a name.
8. import turtle
fred = turtle
fred.shape("turtle")
fred.width(3)
# Define square
def square():
for i in range(4):
fred.forward(100)
fred.left(90)
# This is how to call a function
square()
fred.left(200)
square()
fred.forward(100)
square()
fred.left(200)
square()
9. Continued
# This is a comment, it is ignored
# Comments are used to explain what the code is doing
import turtle
fred = turtle
fred.shape("turtle")
fred.width(3)
# Define square
def square():
for i in range(4):
fred.forward(100)
fred.left(90)
# This is how to call a function
square()
fred.left(200)
square()
fred.forward(100)
square()
fred.left(200)
square()
Editor's Notes
NOTE: To change images on this slide, select a picture and delete it. Then click the Insert Picture icon in the placeholder to insert your own image.
NOTE: To change images on this slide, select a picture and delete it. Then click the Insert Picture icon in the placeholder to insert your own image.