Skip to main content

Lesson 1-11 · Python Functions

Module 1 · Learning to Drive

Lesson 1-11 · Python Functions

50–60 minTransition to Pythondef, parameters, returnSlides (PowerPoint)
👩‍🏫

Teacher mode is on. Toggle it off (bottom-right) to preview the student view.

You built reusable functions with Blockly's "to do something" block back in Lessons 1-3 through 1-5. Now you'll write functions in Python with the def keyword — same idea (define once, call many times), plus the ability to pass in parameters and hand back a return value.

Learning Objectives

By the end of this lesson you will be able to:

  • Define a function in Python with def name(parameters):
  • Call a function with arguments and use the parameters inside its body, including parameters that fall back to a default value
  • Return a value from a function and use it
  • Explain that variables and parameters inside a function are local to it — and why a function can still read a name like drivetrain from the main program

From "to do something" to def​

Here's the reusable square you built in Lesson 1-3, Blockly first and Python below. In Blockly it's two separate things in the workspace — the definition off to one side, and the calls in the main program:

function definition named square
repeat 4 times
Straight cm 30
Turn Deg 90
The definition. It doesn't drive anything on its own — it says what a square is.
square call block
square call block
square call block
The calls. Three squares, three blocks.

In Python both halves live in the same file — the def block first, then the calls underneath it:

def square():
for i in range(4):
drivetrain.straight(30)
drivetrain.turn(90)

square()
square()
square()

The pieces map to what you already know:

  • def — the keyword that defines a function (like the "to do something" block).
  • square — the name (lowercase, words joined by underscores).
  • () — the parameter list (empty for now).
  • : and indentation — everything indented is the function body.
  • square() — calls it. Define it once at the top; call it as often as you like.
Knowledge Check

Which keyword defines a function in Python?

Parameters make it flexible​

Just like the gear icon added an input in Blockly, a name inside the parentheses adds a parameter in Python:

def square(side_length):
for i in range(4):
drivetrain.straight(side_length)
drivetrain.turn(90)

square(30)
square(50)
square(20)

The side_length parameter is a local variable; the numbers you pass (30, 50, 20) are the arguments — the same names you used in Blockly. Add more parameters by separating them with commas: def square(side_length, effort):.

Knowledge Check

Given def square(side_length):, what does calling square(45) make the robot do?

Returning a value​

Some functions do something (draw a square); others calculate something and return an answer. The return keyword hands a value back to whoever called it:

def calculate_angle(sides):
return 360 / sides

angle = calculate_angle(6)
print(f"Hexagon angle: {angle}") # -> Hexagon angle: 60.0

You can then build bigger functions from smaller ones — a polygon that uses calculate_angle:

def polygon(sides, side_length):
angle = calculate_angle(sides)
for i in range(sides):
drivetrain.straight(side_length)
drivetrain.turn(angle)

polygon(4, 30) # square
polygon(3, 25) # triangle
polygon(8, 15) # octagon

Where a variable lives​

Look at angle in that last program. It's created inside polygon, and it's local to it: it comes into existence when polygon starts running, and it's gone the moment polygon finishes. Ask for it from the main program and Python says it doesn't know the name.

def polygon(sides, side_length):
angle = calculate_angle(sides) # angle is born here
... # and dies when polygon returns

polygon(4, 30)
print(angle) # NameError -- there's no angle out here

Parameters work the same way. sides and side_length are locals too; they're just locals that arrive already holding the values you passed in. That's why two different functions can both use a parameter called sides without interfering — each call gets its own.

This is a feature, not a restriction. Because a function's working names are sealed inside it, you can write one without checking what every other function in your program happens to have called things.

So why does drivetrain work?​

Fair question, because it breaks the pattern. Look again:

drivetrain = DifferentialDrive.get_default_differential_drive()

def square(side_length):
for i in range(4):
drivetrain.straight(side_length) # not local -- where's this from?

drivetrain isn't a parameter and it isn't created inside square. It's defined out in the main program, and the rule is this: when Python meets a name inside a function, it looks for a local one first, and if there isn't one it looks outside. So a function can read names from the surrounding program. That's exactly why the three-step XRPLib pattern works — you make the drivetrain once at the top and every function you write can reach it.

Reading outward is fine and this course does it constantly. Assigning to an outside name from inside a function is a different matter, and Python deliberately makes it awkward: writing drivetrain = something inside a function creates a new local by that name rather than changing the outer one. We're not going to need that in Module 1. When you get to classes in Module 2, self. turns out to be the clean answer to "how does an object remember something between calls" — this is the problem it solves.

Knowledge Check

A variable created inside a function (like angle above) can be used…

Knowledge Check

If a function's variables are local, how can square() use drivetrain, which was created in the main program?

Knowledge Check

What's wrong with this? def multiply(x, y)

Giving a parameter a default​

Some functions have an obvious usual answer. If nine calls out of ten are square(30), typing the 30 every time is noise. Python lets you write that usual value into the definition:

def square(side_length=30):
for i in range(4):
drivetrain.straight(side_length)
drivetrain.turn(90)

The =30 doesn't run when the function is defined. It sits there as a fallback for the calls that don't supply one:

square() # no argument given -> side_length is 30
square(50) # argument given -> side_length is 50

Nothing else about the parameter changed. side_length is still a local name that arrives holding a value; all that's different is that the value now has two places it can come from, and the call wins whenever it offers one.

You can give some parameters defaults and leave others without, but there's one rule: the ones with defaults go last.

def polygon(sides, side_length=30): # fine
def polygon(sides=4, side_length): # SyntaxError

Python matches arguments to parameters left to right, so an optional one in the middle would be ambiguous — in polygon(6), there'd be no way to tell whether the 6 is meant for sides or for side_length. Keeping the optional ones at the end means counting from the left always works.

Knowledge Check

Given this definition, what does calling polygon(6) draw?

def polygon(sides, side_length=30):

Activity · Build a shape library​

  1. Write polygon(sides, side_length) and test it on three shapes — the same function you built in Blockly in Lesson 1-5, now in Python.
  2. Add a helper calculate_perimeter(sides, side_length) that returns sides * side_length, and print the perimeter after drawing.
  3. Challenge: give polygon a default side_length, so that polygon(6) draws a hexagon with 30 cm sides. Check that polygon(6, 50) still overrides it.

Real-world connections​

Functions with parameters and return values are the building blocks of every program:

Everywhere

Standard libraries

Languages ship thousands of ready-made functions — you call them without knowing the internals.

Teams

Shared code

Engineers split a big system into functions so many people can work on it at once.

Robotics

Motion & perception

"read distance", "drive to", "plan path" — real robot code is functions calling functions.

Wrap-up​

  • What keyword defines a function, and what punctuation must end the line? (def, and a colon.)
  • What's the difference between a parameter and an argument? (Parameter = name in the def; argument = value in the call.)
  • What does return do? (Sends a value back to whoever called the function.)
  • What does a default do, and where must defaulted parameters go? (Supplies a value when the call doesn't; they go last.)

Resources​