Functions (Intro)
A function is a block of code (or procedure /subprogram / subroutine) that is usually designed to perform a specific task
Functions we have already used:
- It can be called or used from the main program simply by typing in the function's name
- Data can be passed in the call (as parameters) from the main program to be used within the function
- Data can be sent from the function back to the main program (as parameters)
Functions we have already used:
- input
- forward / backward
- left / right
- setposition
Creating Our Own Functions
It is easy to create and use our own functions
def name_function(parameters):
instruction
instruction
instruction
def name_function(parameters):
instruction
instruction
instruction
Example: A function that draws a square when called from the main program
def draw_square(size):
for x in range(4):
shape1.forward(size)
shape1.right(90)
Later in the program, we would call the function
draw_square(25)
def draw_square(size):
for x in range(4):
shape1.forward(size)
shape1.right(90)
Later in the program, we would call the function
draw_square(25)
Part 1: Simple Functions
Start a new turtle python program called "Yourname_Functions_Intro" and be sure to save properly.
Enter the code to do each of the following:
Enter the code to do each of the following:
- Create a function called draw_square and then called it several times to draw a series of perfect squares (single parameter)
- Create a function called draw_rectangle and then call it several times to draw a series of rectangles of differing dimensions (two parameters)
- Challenge: create a function that draws a 5 pointed star. Want more of a challenge, create a function that will draw stars with differing number of points.