Beginner Coding with Blocks
Chapter
>
Level

Advanced Functions and Patterns
Functions with Conditional Logic

Objective

Refill the water and food for the cows by creating a function that handles both types of refills.

The cows could use some more food and water, you don't have any on you but thankfully there are automatic pumps that can refill nourishment for them.

You can create a function with conditional logic that takes a resource parameter and performs different actions based on the value. Functions can contain if blocks inside them to make decisions.

Use the define function block (without return) to create a function named refill. Add a parameter called resource. Inside the function, use if blocks to check if the resource is "food" or "water", and perform the appropriate actions:

  • If resource is "food": use the place block with "food", then use the speak block with the food_amount constant
  • If resource is "water": use the water block, then use the speak block with the water_amount constant

Functions with conditional logic inside allow you to create reusable code that can handle different situations. You can call the same function with different arguments, and it will perform different actions based on the value.

Using this function you are able to refill nourishment for the cows, walk to the light X marks in order to refill "water" and walk to the dark X marks in order to refill "food". Call the refill function with the appropriate argument at each X mark.

Refill all four (4) trays in the field to complete your objective and provide nourishment for the animals.

Code book