Skip to main content

Functions

Reusable Blocks of Code

· 3 min read

In the previous unit, we used loops to repeat code. But what if you want to reuse the same block of code in different places? That's what functions are for. They let you define a block of code once and call it whenever you need it.

Functions

Defining and Calling Functions

You define a function with the def keyword, followed by a name and parentheses.

def my_function():
print("Hello, World!")

To run the code inside the function, you call it by name with parentheses:

my_function()

This prints "Hello, World!" to the console. The code inside the function only runs when you call it.

Parameters and Arguments

Functions become more useful when they accept input. You define parameters inside the parentheses, and pass arguments when you call the function.

def greet(name):
print(f"Hello, {name}!")

greet("Alice")

This prints "Hello, Alice!" The variable name inside the function gets the value "Alice" that we passed in.

The f before the string creates an f-string (formatted string literal). Anything inside {} gets evaluated and inserted into the string. It's a clean way to build strings with variable values.

You can have multiple parameters, separated by commas:

def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")

greet("Alice", "Smith")

Return Values

Functions can send values back using the return statement.

def multiply(x):
return 5 * x

result = multiply(3)
print(result)

This prints 15. When Python hits return, it exits the function immediately and passes the value back to wherever the function was called. You can store that value in a variable or use it directly in an expression.

Project: Draw Patterns with Functions

Let's use functions to organize our Turtle code. We'll create a reusable function that draws a square, then call it multiple times to create a pattern.

import turtle

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()

def draw_square(turtle, side_length):
for _ in range(4):
turtle.forward(side_length)
turtle.right(90)

for _ in range(36):
draw_square(t, 100)
t.right(10)

t.hideturtle()
turtle.done()

The draw_square function takes two parameters: the turtle object and the side length. Inside, a loop draws the four sides. The function doesn't know or care about the bigger pattern. It just draws one square.

The main loop calls draw_square 36 times, rotating the turtle 10 degrees between each call. The result is a spiral pattern of overlapping squares. Try changing the rotation angle or the number of iterations to create different patterns.

In the next unit, we'll look at lambda functions, a compact way to define small, anonymous functions.