🤖

Teaching Carol to Turn Right

Oct 4, 2024

Lecture Notes: Teaching Carol to Turn Right

Introduction

  • Carol the robot cannot naturally turn right.
  • In the "Make a Tower" exercise, a situation arises where Carol needs to turn right.

Standard Commands for Carol

  • Carol originally knows only four commands.
  • Turning right is not one of them.
  • Alternative method:
    • Turn left three times to simulate a right turn.

Introducing Functions

  • Functions allow us to teach Carol new commands beyond the original four.
  • Terminology:
    • Functions may be called procedures, tasks, or processes.
    • In this context, we're focusing on functions.

Creating a Turn Right Function

  • Defining a Function in Python
    • Use def followed by the function name and parentheses.
    • End the definition line with a colon.
    • Indent commands in the function body.
    • Example to turn right using three left turns: def turn_right(): turn_left() turn_left() turn_left()

Importance of Function Order in Python

  • Functions must be defined before they are called in the code.
  • Python reads code from top to bottom.
  • Calling an undefined function results in an error.

Example Walkthrough: Making Carol Turn Right

  • Initial Steps
    • Use commands like move, put_ball, etc.
    • Adjust Carol's direction using turn commands.
  • Implementing Turn Right
    • Attempting to use turn_right without definition results in an error.
    • Substitute three turn_left commands to proceed.
  • Defining the Turn Right Function
    • Place function definition at the top of the code.
    • Ensure correct indentation for function body and other code segments.
    • Avoid errors by ensuring all parts of the function are correctly indented.
  • Executing the Defined Function
    • Code skips the function definition when executed until the function is called.
    • Call turn_right() to execute the new command.

Conclusion

  • Successfully taught Carol a new command to turn right using functions.
  • Encouragement to experiment with code in the editor.