Turtle Graphics
Function Return Value
Functions can also return a value which was calculated or generated inside the function to the calling statement line. The value of newSize in function drawASquareAndMoveBack
is returned (sent) to the statement line size = drawASquareAndMoveBack("Red", size, spacing
where the size variable is assigned to that value after the function completes its execution. So the return keyword is a reserved word in Python, that is used to send a value back to the calling statement:
import turtle
def draw_a_square_for_me(squareSize):
turtle.forward(squareSize)
turtle.right(90)
turtle.forward(squareSize)
turtle.right(90)
turtle.forward(squareSize)
turtle.right(90)
turtle.forward(squareSize)
turtle.right(90)
def move_turtle_back(squareSpacing):
turtle.penup()
turtle.backward(squareSpacing)
turtle.left(90)
turtle.forward(squareSpacing)
turtle.right(90)
turtle.pendown()
def draw_a_square_and_move_back(square_color, size_of_square, space_between_squares):
turtle.pencolor(square_color)
draw_a_square_for_me(size_of_square)
move_turtle_back(space_between_squares)
newSize = size_of_square + 2 * space_between_squares
return newSize
size = 100
spacing = 5
turtle.penup()
turtle.goto(-1 * size / 2, size / 2)
turtle.pendown()
turtle.pensize(5)
turtle.speed(7)
spacing = spacing + 5
size = draw_a_square_and_move_back("Red", size, spacing)
spacing = spacing + 5
size = draw_a_square_and_move_back("Blue", size, spacing)
spacing = spacing + 5
size = draw_a_square_and_move_back("Green", size, spacing)
spacing = spacing + 5
size = draw_a_square_and_move_back("Yellow", size, spacing)
spacing = spacing + 5
size = draw_a_square_and_move_back("Orange", size, spacing)
spacing = spacing + 5
size = draw_a_square_and_move_back("Pink", size, spacing)
turtle.done()
return
statement will not output anything on the terminal screen by itself. You should not confuse it with print
which is used for outputting its arguments on the terminal. It is possible to print
a value returned
from a function.
def square_function(number):
return number * number
square_value = square_function(5)
print(square_value)
See the following:
def some_function():
text1 = "The print was called from"
text2 = "the method named some_function"
print (text1, text2)
return "another message"
text_received = some_funtion()
print(text_received)
print: Immediate display of the message.
return: Send value to be used by the calling statement.
If you do not specify any value after the return
keyword it will simply terminate the function without sending any value to the calling statement.