Tutorial 4: Bearcu Learns Tricks
Learning Goal: Functions
You've been repeating similar code patterns. Functions let you group commands together and reuse them!
A function is defined with def, given a name, and contains
indented code. You can then "call" the function by using its name with
parentheses.
def turn_around():
bearcu.turn_left()
bearcu.turn_left()
# Now you can use turn_around() anywhere!
turn_around() # Bearcu turns 180 degreesFunctions help you:
- Avoid repeating the same code
- Make your code easier to read and understand
- Fix bugs in one place instead of many places
Tutorial 4: Bearcu Learns Tricks
Bearcu needs to navigate in a square pattern to reach the goal.
Instead of writing the same code over and over, you can define a function! A function is like teaching Bearcu a new trick that can be used multiple times.
Complete the move_and_turn() function and call it enough times to reach the star!
Initializing Python environment...
Loading grid...
What You Learned
- Define functions with
def function_name(): - Function bodies must be indented
- Call functions by writing their name with
() - Functions can contain loops, conditionals, and other commands
- Good function names describe what they do