CS106A - Lecture 1 - Code and Bit
Today: Bit, code, functions, and the while-loop
- The computer is powerful
- But dumb! Just runs code mechanically
- You have insight
Think of an algorithm
Express ideas in code
Dumb it down so even a computer can do it
- A great combination
- Your insight, driving the computer
Heads Up - Lots of Shallow
- We are moving fast right here at the start
- I need to show 10 little things for anything to work
- They are weird looking
- They are numerous but not that difficult
- So just hang in there for a couple lectures
Background - Program and Functions
A "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 the sentences of 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:
Bit's World - Simple
We have this "bit" robot, lives in a rectangular world divided into squares, like a chessboard. We'll use bit at the start of CS106A to introduce and play with key parts of Python. The nice thing about Bit code is that each action has a tangible result, as bit move around in the world.
Bit can do 4 actions in the world:
move, left, right, paint
Here is a more detailed guide of Bit's features: Bit Reference
For now we'll just jump in with an example.
Bit1 Example - Syntax
Here is the Python code for one function that moves bit around a little. There is syntax here - not pretty, but easy enough to get used to.
Suppose Bit starts at the upper left corner facing to the right, and then the following code runs:
bit = Bit(filename) # Creates the "before" picture
Let's Run This Function
- Run a function = runs its lines top to bottom (aka "call" that function)
- Each line does something
- In this case, for each line see bit take an action
Here is a "live" on the web version of the above def. Click "Run" on the page and watch what it does. You can use the "steps" slider to run the code forwards and backwards, seeing the details of the run.
> do_bit1() example
There's a lot to see with this first example - what do we see here?
1. What does "Run" of a function do?
- Running a function, aka "calling" that function
- e.g. here we have a function named "do_bit1"
- The function contains indented lines of code
- Running the function, runs those lines
run one line at a time
run them from top to bottom
2. What Does
- There is an existing function named "move" that Bit understands
The function moves bit forward one square
- The syntax
bit.move() "calls" that function
i.e. runs it
- Calling a function runs its lines, then continues to our next line
- This is the "object oriented" or "noun.verb" style of function call
- Note the parenthesis at the right side of the call
The call does not work without the parenthesis - syntax!
3. What Does
- There is an existing function named "paint" that Bit understands
It colors the square bit is on
- The paint function takes a "parameter" - extra information to use
- The parameter value we want to use is written inside the parenthesis of the call
- Means: run the paint() function, passing in 'blue' as the parameter value
4. Def Syntax
Here is the Python code for the "do_bit1" function
bit = Bit(filename)
So having seen a function run, now look at the details of the syntax. Sorry, it's a bunch of small syntactic points.
The def syntax looks weird, but is basically superficial and you will get used to it quickly.
The first code line sets up a variable named "bit" to point to the robot-world as pictured above. The first line sets up the bit world, and we're going to gloss over how that works for now.
- 1. The definition of a functoin starts with the word "def"
- 2. Followed by a name for the function, e.g. "do_bit1".
The name is chosen by the programmer
Name is often verb-like, referring to what the function does
Multiple words are separated by underbars
- 3. Followed by a parenthesis pair with colon at the end
- 4. Followed by the lines of code of the function, indented
- 5. Running, aka "calling", a function runs its lines from top to bottom
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.
- Syntax - code is structured for the computer
Remember the computer is kind of dumb!
- Very common error - type in code, with slight syntax problem
- e.g. syntax error:
- Professional programmers make that sort of "error" all the time
- Just type it in, run it, fix the errors
- Not a reflection of some flaw in the programmer
- Do not give in to the following thoughts (imposter syndrome):
"Another syntax error .. maybe I'm not cut out for this!"
"I bet nobody else is getting these"
- Just the nature of typing ideas into the mechanical computer language
- Fixing these little errors is a small, normal step
- The computer is a powerful tool in your hands
But you need to talk to them their way on syntax
Error Exercise - Sport and Fix!
- Exercises to desensitize: a bunch of typical syntax errors, see them and fix them
- These all have errors, trying run and fix (lecture demo, or on your own)
- Would a human understand what these mean, even with the errors?
- These are on the experimental server, uses your Stanford login
- Some common errors
(Can try manually adding these errors to a working do_bit1)
Uneven indentation within def
Mess up or omit
() on function call
: on the def line
Typo the name of a function, e.g.
(optional) You Try One: green2
Here is an exercise like bit1 with the code left for you to do.
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:
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
Suppose I Give You This Go-Green Problem
Bit starts at the upper left as usual. Move bit forward until reaching a wall, painting every moved-to square green. The resulting world looks like:
- Looks like a lot of work + tedious
- To make all that green, lots of these two lines
- Need to stop when reaching far wall
- Q: How to do this?
- A: Loops
Run go-green code
First we'll run the code. This code is complete. Watch it run to get a feel for how the loop works.
Checkmark / Diff Features
- The system knows what the world is supposed to look like when the code works correctly
If the output is correct - green checkmark
- "diff" Feature - diagonal red marks on incorrect squares
The system knows what the world is supposed to look like, so marks differing squares
- Test if way-forward is clear before a move:
bit.front_clear() returns either
The True/False is returned to the
front_clear() call spot in the code
There are the two "boolean" values
- Today: use as test-expression in while
For reference, here is the code:
bit = Bit(filename)
While Loop Syntax
Syntax 4 parts:
while, test-expression, colon, indented body lines
body lines inside the while
While Loop Operation
- First evaluate test-expression at the top, True or False?
- If True, run all the lines of the body, top to bottom
Then loop back to top, check test again, .. repeat
After every run of the body .. go back and do the test
- When the loop-test is False, loop is done, running continue after the loop body
- If the test is False initially, the body runs zero times (see Case-4)
While Loop Observations
- Lines before and after loop run once, as usual
- Body lines in the loop are different, running many times
- It's possible for the body to run zero times
One Code - Many Cases - Generality
- There is one copy of your code algorithm
- General = it should work for all the different input worlds
- Try Run All option to really see this
While Loop - Power!
- Loops are a big jump up in power
- "Do these lines again and again"
- Every algorithm has key lines to run thousands or millions of times
- Several types of loop - today while
We'll pick up with more while-loop driven exercises next lecture.