CS106A - Lecture 1 - Code and Bit

Today: Bit, code, functions, and the while-loop

Heads Up - 10 Little Things

Background - The Programmer and the Computer

This is the zoomed out background of the whole course.

Computers are invaluable, solving real problems in the world. But what is the structure between the real world and the computer? alt: person has idea, translates the idea into code for the computer

You have an insight about something useful to do in the world, an idea. You structure and translate the idea into code. Dumbing it down, essentially, to the language where the computer can handle it. The computer is very powerful in its way, but can only deal with simple, mechanical inputs, which is why programmers exist. As you endure countless obscure failures and error messages from the computer, keep in mind that the computer just does what it is told. The actual idea comes from you.

Program Made of Functions

A computer program (or "app") is a collection of code for the computer to run. The code in a program is divided into smaller, logical units of code called functions, much as all the words that make up an essay are divided into logical paragraphs.

Python programs are written as text in files named like "example.py". The program text will be divided into many functions, each marked by the word def:

alt: program is made of functions, each with def


Bit Robot - Getting Started

We have this "Bit" robot, lives in a rectangular world divided into squares, like a chessboard. Bit is my research project - open it up to the world soon. We'll use bit at the start of CS106A to introduce and play with key parts of Python. The code driving Bit around is 100% Python code. The nice thing about Bit code is that the actions have immediate, visual results, so you can see what each line of code does.

Here is bit in two sentences: bit moves from square to square, can paint the square it is on red, green, or blue. Black squares and the sides of the world are blocked - bit cannot move there.
alt: bit in world of squares; squares are painted, empty, or black-blocked

For reference, here is a more detailed guide to Bit's features: Bit Reference

Bit can do 5 actions in the world: move, left, right, paint, erase

For now we'll just jump in with an example.

Example do_bit1() Function

Below is the code in a Python function named "do_bit1" that creates bit in a little world and commands bit to do a few things. There is syntax here - not pretty. We'll focus on what bit does for each line.

def do_bit1(filename):
    bit = Bit(filename)  # Creates "before" picture
    bit.move()
    bit.paint('blue')
    bit.right()
    bit.move()
    bit.paint('green')

1. The function starts bit off facing the right side of the world with a couple empty squares in front (before-run picture):
alt: bit in empty world

2. The code in the function moves bit over a couple squares, painting some of them. So running the function does those actions, and afterwards the world looks like this (after-run picture):
alt: bit in world with 2 squares painted

Run It First - Experimental Server

Here is the bit1 problem on the experimental server (you can run it too, or just watch):

> do_bit1() function

We'll use Nick's experimental server for code practice. See the "Bit1" section at the very top; the "bit1" problem is there. Often the code in a lecture example like this will be incomplete, and we'll work it out in lecture. There is a Show Solution button on each problem, so you can always play with it again later and check your answer.

Run It

Click the Run button and see what the function does. See how bit takes actions in the world first, and then we'll fill in what's going on with the lines of code. You can use the "steps" slider to run the code forwards and backwards, seeing the details of the run.


Now let's look at all of that syntax, discussing what each line of code does.

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

1. Run a Function = Run Its Lines

The Run button in the web page runs this do_bit1 function, running its lines of code from top to bottom. Running a function is also known as "calling" that function. In this case, each line in the function commands bit to do this or that, so we see bit move around as the function runs from top to bottom.

2. bit = Bit(filename) - Set Up World

This line creates the world with bit in it, and sets the variable bit to point to the robot. We needs this line once at the top to set things up, then the later lines use the robot. We'll explain this with less hand-waving later. This drawing shows the setup - the bit robot is created along with its world, and the variable bit is set to point to the robot.
alt: bit in empty world

3. bit.move() = Call the "move" Function

4. bit.paint('blue') = Call the "paint" function

5. Other functions: bit.left() and bit.right()

6. def = Define a Function

Now we'll go back and talk about the first line. This defines a function named do_bit1 that holds the lines of code we are running.

def do_bit1(filename):
    bit = Bit(filename)
    bit.move()
    bit.paint('blue')
    ...

A Little Talk About Syntax Errors

"Syntax" is not a word that regular people use very often, but it is central in computer code. The syntax of code takes some getting used to, but is not actually difficult.

"Bit Errors" Exercise - Sport and Fix!


(optional) You Try One: bit2

> bit2 exercise

alt: 2 squares below start square are now green

Try that one on your own to practice the basic Bit functions, but we're not doing it in lecture. There's a few problems in there for more practice.

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

The word pass is a placeholder for your code, remove it. Conceptually this does not look hard, but expect to make some mistakes as you get the little syntax and naming details right as required by the (lame, needy) computer


Aside: Checkmark / Diff Features


Loops!

Now we'll look at the "loop" structure which is very powerful

We'll see how far we get with this in lecture-1.

Suppose I Give You This go-green Problem

Bit starts at the upper left square as usual. Move bit forward until blocked by a wall, painting every moved-to square green.

alt: bit moves across top of world, painting every moved-to square green

Run go-green code

Follow the link to the go-green problem. The code there is complete, so just watch it run a few times to get a feel for what the loop does, and then we'll look at the details.

> go-green

While Loop

The loop is a big increase in power, running lines many times. There are a few different types of loop. Here we will look at the while loop.

Go-Green Loop Code

...
while bit.front_clear():
    bit.move()
    bit.paint('green')

While - How Does It Stop?

While Loop Syntax

The while loop syntax is made of four parts: the word while, a test expression, a colon (:), and on the next line indented body lines to run.

while test-expression:
    body lines

While Loop Sequence

This diagram shows the sequence between the while loop test and the body:

alt: while has test and body

How the While Loop Works

There is not much to say about the body; it is just a series of lines to run. The test expression is more interesting, controlling the run of the loop.

bit.front_clear() Expression

An "expression" is a piece of code that, when it runs, returns a value to that spot in the code.

In Bit's world, the way forward is clear if the square in front of Bit is not blocked by the edge of the world or a solid black square.

Bit has a function front_clear() that checks if the square in front of bit is clear for a move — returning True if the way is clear, and False otherwise.

Here is a visualization of how the bit.front_clear() expression works in the code, with the True or False result value coming out of the expression:

alt: front_clear() returns False when square in front is blocked - either a black square or an edge of the world

Optional: Go-Left, Go-Right Exercises

We'll continue with while loops next lecture. If you'd like to play around with some code which is similar to go green try writing the code for go-left first. The word "pass" is a placeholder in Python that does nothing. For exercises, replace the word "pass" with your code.

> go-left

The go-right exercise requires two loops - write one loop to go to the right corner. Write a second loop to go down. The first loop and the second loop should be at the same indentation, not one inside the other. Note that all these problems have a Show Solution button, so you can play with them without writing the code.

> go-right