CS106AP - Lecture 1 - Code and Bit

CCS106A: Computer - Code - You


Story #1 - Bit's World - Simple

We have this "bit" robot, lives in a rectangular world. Use this just at the start of CS106A to get things going.

Bit can 4 things, move, left, right, paint .. show b

Bit Reference - more detailed list of Bit features

Suppose Bit starts at the upper left corner facing to the right, and then the following code runs:

    bit.move()
    bit.paint('blue')
    bit.right()
    bit.move()
    bit.paint('green')

Before:

alt bit in empty world

After:

alt: bit in world with 2 squares painted

The syntax bit.move() is a Python function call. A function hold some code. To "call" a function runs its code. This is the noun.verb function call form.

Story #2 - Running Python Code

Now look at a def that has those same steps as formal Python code:

Bit blue_green() def

Here is complete Python function that does those same steps:

def blue_green(filename):
    bit = Bit(filename)
    bit.move()
    bit.paint('blue')
    bit.right()
    bit.move()
    bit.paint('green')

Before Running

Here is a "live" on the web version of the above def. Click "Run" on the page and watch what it does. Use the steps slider.

> bit1 blue_green function

Story #3 - 6 Things About def Syntax

So having seen a function run, now look at the details of the syntax. Sorry, it's a bunch of small syntactic points.

Looks weird, but is basically superficial and you will get used to it quickly.

def blue_green(filename):
    bit = Bit(filename)
    bit.move()
    bit.paint('blue')
    bit.right()
    bit.move()
    bit.paint('green')

The first code line sets up the bit-arrow as pictured above, explained in a later lecture
bit = Bit(filename)


A Little Talk About Syntax Errors

Code Demos - Get Errors - Fix!

You Try One: green2 (if we have time)

Bit begins at the upper left corner facing right. Paint the square below the start square green, and the square below that green as well, ending like this:

alt: 2 square below start square are now green

The word pass is a placeholder for your code, remove it. Feel free to make some syntax errors getting this to work!)

> green2