Introduction to Functions
Swipe to show menu
As challenges grow, you will often need the Ninja to group a sequence of actions into a single reusable command that can be called whenever needed.
For example, imagine there are 2 sushi tiles in the same pattern on the map. The Ninja needs to approach each one, pick it up, and continue. Copying the same code every time works, but it quickly becomes messy and takes time. Functions solve this problem.
A function lets you group several commands into a single action and give it a name. Once defined, you can run that action whenever you want with just one line of code. Think of a function as a custom move you teach your Ninja.
Here is what the code might look like without using functions:
ninja.py
Here, 2 groups of movements are logically repeated.
Creating Your First Function
Now turn that repeated logic into a function:
def collect_sushi(ninja):
ninja.go_right()
ninja.go_right()
ninja.pick_sushi()
Here is what is happening:
defstarts a function definition;collect_sushiis the function's name;ninjais a function's parameter;- The indented lines are the commands the function runs.
Calling a Function
Once the function is defined, you can use it like this:
collect_sushi(ninja)
collect_sushi(ninja)
Try this:
ninja.py
All code inside a function must be indented under the function definition.
For example, the code below does not work because it is not indented correctly:
def collect_sushi(ninja):
ninja.go_right()
ninja.go_right()
ninja.pick_sushi()
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat