CS106A, Summer 2022
Slide 1
Welcome to CS106A!
- Instructor - Chris Gregg
- CS lecturer
- At Stanford for 6 years
- B.S., Johns Hopkins, Electrical Engineering
- MEd., Harvard, physics teaching
- Ph.D., University of Virginia, Computer Engineering
- U.S. Navy, 7 years active duty, 15+ years reserves, Commander
- Taught high school for 7 years, Brookline, MA, Santa Cruz, CA
- I love to tinker! Ask me about my typewriter projects!
- You can call me Chris (Dr. Gregg is fine, but students usually call me Chris)
- Head TA - Tori Qiu
- Lots of Section Leaders!
- Section preference signups are open. The preferences will close on Tuesday at 5pm. You will find out your section assignments via email Tuesday night, and sections start on Wednesday.
- CS106A teaches basic coding and problem solving
- like swimming, you can't just read about it
- No prior experience required
- We are careful to go step by step
- Code looks impossible...
- You'll be amazed at what you can build
- Slides for CS106A are based on slides by Nick Parlante, who designed this version of CS106A
Everything is Code
What's going on in the world today changing your life: phones, video streaming, deep fakes, twitter, lots of online communities, self driving cars, online censorship. How do all these work? Code. Knowing about code seems like a good idea.
Slide 2
Why Take CS106A?
- No Longer be Intimidated
- The nature of computers is code
- Understand how computers fit in the world
- Not some hocus-pocus mythology of computers
- Computing is a lot simpler (dumber?) than you might think
- Solve Coding Problems
- Python is powerful
- In 8 weeks, you'll learn enough to solve real problems
- Many CS106A projects have neat, tangible output
- Hidden Agenda
- You might find you like it
- Take CS106B
- We have a whole department on this stuff!
Slide 3
Links on Course Page
- https://cs106a.stanford.edu - everything is there
- Tori - our super head TA
- Contact her if you need a problem solved
- Please send her any OAE letters
- Office Hours - Chris and Tori
- This is a Python Guide for the course
- Videos wil be available after lecture on canvas
- Please stay on top of the lectures!
- In section, the expectation will be that you have watched the lectures. If you cannot participate well in section becasue you haven't seen the lectures, your grade will suffer.
Slide 4
Python Language
- Using Python3
- Python is "programmer friendly"
- get things done easily
- Not just for CS people
- Very popular for data, all sorts of things
Slide 5
Pedagogy Notes
- Lab in lecture - reinforce
- Education research, Carl Wieman (Stanford)
- Do a little activity with what you just saw
- Lecture to homework, just a few days
- You don't learn to code from lecture (sadface.gif) – you learn from writing code yourself.
- You learn the big ideas and the important things to focus on from lecture
- You practice in Section and on the assignments
Slide 6
Lecture Notes
- I'll provide notes like this each day
- May include links to live code to try
- I go through pretty fast … do examples etc.
- You know you can review later, look at with your SL etc.
- You want to be able to solve the problems I do in lecture yourself
Please read the syllabus for other details.
Slide 7
Let's start coding!
- 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
Dumb it down so even a computer can do it - A great combination
- Your insight, driving the computer
Slide 8
Heads Up - 10 Little Things
- We are moving fast right here at the start
- You need to know about ten little things for anything to work in Python
- Some of theose things are weird looking
- But they are not that difficult
- So just hang in there for a couple lectures
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, who 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.
Here is what Bit looks like:
Bit can do 4 actions in the world: move
, left
, right
, and 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):
Slide 9
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 Parlante'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.
Slide 10
2. bit.move()
= Call the "move" Function
- There is a function named "move" that Bit understands
The function moves bit forward one square Note that the perspective is a bit wonky: "forward" is always in the direction that Bit is facing. Think of the diagram from above with Bit facing to the right, left, up, or down. - 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!
Slide 11
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'
Slide 12
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
Again: the perspective is a bit strange.
bit.left()
andbit.right()
always rotate Bit, regardless of the direction Bit is currently facing. - 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.
Slide 13
- The definition of a function starts with the word:
def
- 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 - Followed by a parenthesis pair, not explained today, ending with a colon
- 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
Slide 14
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
Slide 15
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!
Slide 16
- 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
Slide 17
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()
(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 (lame, needy) computer
Slide 18
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
Slide 19
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
Slide 20
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
Slide 21
bit.front_clear()
- Test if the way forward is clear before a move:
bit.front_clear()
- Calling
bit.front_clear()
returns eitherTrue
orFalse
The True/False is returned to thefront_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
Slide 22
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)
Slide 23
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
Slide 24
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
Slide 25
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. Â