Lecture 1: Part 1 Welcome
June 21st, 2021
CS106A - Lecture 1 - Code and Bit
Today: Bit, code, functions, and the while-loop
- The computer is powerful
- But the computer is so stupid!
- It runs code mechanically
- You have insight
- Think of an algorithm
- Express ideas in code
- Tell the computer what to do
- You and the computer are a great combination
- Your insight, driving the computer
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:
Bit Robot - Getting Started
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 code driving Bit around is 100% Python code. The nice thing about Bit code is that the actions have tangible results, so you can see what the code is doing.
Bit can do 4 actions in the world: move, left, right, paint
For later reference, here is a more detailed guide to Bit's features: Bit Reference
For now we'll just jump in with an example.
Example do_bit1() Function
Below is a code in a Python function that creates bit in a little world and commands bit with a few actions. There is syntax here - not pretty. Don't worry about all the syntax in there just yet. First let's see what it does.
def do_bit1(filename):
bit = Bit(filename) # Creates the "before" picture
bit.move()
bit.paint('blue')
bit.right()
bit.move()
bit.paint('green')
1. The function starts bit off in the upper left square of the world, like this (before-run picture):
2. The code in the function moves bit over a few squares, painting some of them. So running the function does those actions, and afterwards the world looks like this (after-run picture):
Run It First
- Before looking at the code details
- Run the function to see what it does
- Run a Function = run its lines top to bottom
Also known as "calling" the function
- Each line does something
- In this case, for each line see bit take an action
1. Experimental Server
Here is the bit1 problem on the experimental server: do_bit1() example
We'll use Nick's experimental server for code practice. See the "Bit1" section at the very top; the "do_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.
2. Run It
Click the Run button and see what it 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 to see how this works.
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 function here, do_bit1, has lines of code in it. Clicking the Run button runs that 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.move()
= Call the "move" Function
- There is a function named "move" that Bit understands
The function moves bit forward one square
- The syntax
bit.move()
calls the "move" function
- 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
bit.move()
The call does not work without the parenthesis - syntax!
3. bit.paint('blue')
= Call "paint" function
- There is a 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 within the parenthesis
- e.g.
bit.paint('blue')
- Means: run the paint() function, passing in
'blue'
as the parameter value
- The paint function works with the three parameter values:
'red' 'green' 'blue'
4 Other functions: bit.left()
and bit.right()
- There are also functions named "left" and "right"
- These turn bit left and right 90 degrees in the world
- The syntax to call these functions is the same, e.g.
bit.right()
5. Def Syntax
Here are the first few lines of this Python example:
def do_bit1(filename):
bit = Bit(filename)
bit.move()
bit.paint('blue')
...
This is a def which defines a new function in Python.
- 1. The definition of a function starts with the word:
def
- 2. Followed by a name for the function, e.g.:
do_bit1
The name is chosen by the programmer
We'll have better examples later, we promise
Name is often verb-like, referring to what the function does
Multiple words are separated by underbars
- 3. Followed by a parenthesis pair, not explained today, ending with a colon
- 4. All the later, indented lines are the lines which make up this function
In this case the lines move bit around
- Summary: a function = a name + a bunch of lines of code
6. bit = Bit(filename)
- This line sets up bit for the later lines
- We will explain this in more detail later
- The drawing below shows how the variable
bit
is set to point to the robot in memory
- So later lines like
bit.move()
command that robot
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:
bit.move[)
- 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
"Bit Errors" Exercise - Spot and Fix!
- Exercises to desensitize: a bunch of typical 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
- Compile Error - syntax problem, code does not run
- Runtime Error - code runs, then hits an error on some line
The program halts on the error line
Bit gets a funny "error" expression
- biterr1 syntax error
- biterr2
- biterr3
- biterr4 runtime error
- biterr5
- biterr6
Other Errors
- Some other error forms, can try adding these manually in do_bit1
- Uneven indentation within def
- Missing colon
:
on the def line
- Mess up or omit parenthesis on a function call, e.g.
bit.move
- Typo the name of a function, e.g.
bit.mve()
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
(optional) You Try One: bit2
Here is an exercise like bit1 with the code left for you to do.
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 (needy) computer
> do_bit2() example
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
bit.move()
bit.paint('green')
- 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.
> go-green
Statement vs. Expression
- A line of Python code may be a statement or an expression
- A statement runs code that performs an action
- e.g.
bit.move()
- An expression runs code and returns a value to that spot
- e.g.
bit.front_clear()
which returns True or False to its spot
- Lots more examples later of statement vs. expression
bit.front_clear()
- Test if the way forward is clear before a move:
bit.front_clear()
- Calling
bit.front_clear()
returns either True
or False
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
go_green() Code
For reference, here is the code:
def go_green(filename):
bit = Bit(filename)
while bit.front_clear():
bit.move()
bit.paint('green')
While Loop Syntax
Syntax 4 parts: while, test-expression, colon, indented body lines
while test-expression:
body lines inside the while
indented
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 in a function
- 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
- "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, next week for
We'll pick up with more while-loop driven exercises next lecture.