fbpx

Functions

Functions are ways for us to have a program remember code we already wrote and do it again. They’re like recipes.

We can use functions to teach Tina how to do new things. We make a function by typing def, then the function name, a pair of parentheses (()), then a colon (:). Here’s the beginning of a function named first_function:

def first_function():

After a funtion is defined, we can put code inside of it by indenting it. Indenting means having four spaces on the front:

def first_function():
    print "This line is indented 4 spaces!"

Once a function is defined, we can call it by typing its name and a pair of parentheses (()). Here’s how we’ll call our first_function():

first_function()

When we do this, everything inside the function will happen.

In this example, there’s already a function called triangle() defined for you, and it is called one time. Call it one or more times and see what happens…

 

Assignment:

You can  modify this program:

  • Change what the triangle() says and Tina will do your new instructions.

  • Try writing your own function and calling it as well!

Functions are recipes, but we can also give them special inputs called parameters that can make them slightly different each time.

The x and y coordinates are parameters. To make a function that accepts a parameter, we include its name inside the parentheses when we define it.

Example:

def my_function(parameter):
print(parameter)

my_function(“Hello!”)
my_function(“Bonjour!”)

Output:

Hello!
Bonjour!

In the example above we call my_function twice, once with a parameter we defined as “Hello!”, and another time with the parameter “Bonjour!”. The function does the same thing, print the parameter, but we get to tell it what to print.

This means that we can write a function that tells Tina how to print different things.

We can  modify this example so that the function say() is called with different parameter inputs.

In this code say() function is defined to tell Tina what to say.

Assignment:

  • Tina will need anything she says to be in quotes (") so she can read it.

  • You can make Tina say even more things! Just add another line with say("Your message here")