Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.

Learning to Program
Navigate With Left And Right Keys
Learning to Program
The Four Pillars of Programming*


*as I see them

To write programs in many languages, all you need to know are four things:

  • Statements
  • Variables
  • Conditionals
  • Loops
Statements

Statements are the commands that make a computer do something:

  • Perform a calculation
  • Search for a name
  • Save information in a file
  • Draw a picture on the screen
  • Turn a motor on
  • Get input from a sensor

Variables

Variables are symbolic names we give to things so you and the computer can share that name for something and remember later. These names can be almost anything allowed by the programming grammar.

It's important to use the exact name we gave to a variable, otherwise the computer program won't know what we're asking for.

Conditionals

Conditionals are what make a program seem smart, able to make choices. Programs can make choices based on the things it knows and choose accordingly.
Should the robot turn left or right? Basically, if "something" happened, then "do these things"

Loops

Loops provide a great deal of the power a computer has. They allow a program to do one or more statements many times very quickly. If you want a program to do something over and over again, it always goes in a loop.

Let's talk more about these four things...


And let's use the Python language to do it
Statements
Statements

Statements, and sets of Statements, are what make a computer actually do something. When you click on a button on the screen, behind the scenes program statements are being run.

Statements

If you are familiar with the command line, when you type "dir" and hit enter, you're telling the computer to generate a list of files from the current directory and print that list to the screen.

Statement Examples

Programs also give Statements to the computer telling it what to do. In this example we're having Python give a statement to the computer telling it to get a listing of files from the current directory.

                            
    os.listdir(".")
    ['lib', 'spike', '.directory', 'plantlib.pth',
    'var', 'images']
                            
                        
In this example Python got the directory list, but having no where to put it, it just printed it to the screen.

Statement Examples

Most of the time when writing programs, we want to save the results of a statement in a variable* to use later. Here we're doing the same thing we did before, but assigning the results of os.listdir(".") to the variable file_list, and then printing the variable file_list to the screen.

                            
    file_list = os.listdir(".")
    print file_list
    ['lib', 'spike', '.directory', 'plantlib.pth',
    'var', 'images']
                            
                        
*We'll get to variables in a minute.

Statement Examples

Statements are usually simple, relatively small actions we want the program to take, like assigning the results of a calculation to a variable, or opening a file we want the program to read information from.

                            
    count = current + 1
    pi = 3.14159
    file = open("diary.txt")
                            
                        
In programming we combine these simple statements to create more interesting, complex behaviors we want our programs have.

Statement Creation

Programming languages come with a large set of statements built in. They also have the ability to add more statements used for specialized tasks, like graphics or gaming. These extra statements are available by using libraries in your program. You can also create your own statements by combining statements that you'd like to use over again into something called a function*


*We'll talk more about functions later on

Variables

Variables can be tricky

It seems like variables are easy to understand, but it's not always clear why we need them in order to write programs. In people terms a post-it note acts like a variable, we use it to remember something for later. A variable has the same purpose in a program.

People can remember all kinds of things, but computer programs can only remember a small set of different kinds of things. Since everything a program remembers is a variable, there are different types of variables.

Common Variable Types
  • Integer - a whole number, like 12
  • Double - a decimal number, like 12.95
  • Character - a single letter, like "c"
  • String - a collection of characters, like "robots"
  • Boolean - a variable that can be either True or False
Variable Examples

Let's declare some variables and assign a value to them. In the example below we're creating an Integer variable named "count" with a value of 12. A Double variable named "price" with a value of 12.95. And lastly a String variable named "person" with a value of "Stewie Griffin"

                            
    count = 12
    price = 12.95
    person = "Stewie Griffin"
                            
                        
The mathmatial equal sign "=" creates the variable and assign a value to it. This is how Python does this.

Collections of Variables

Quite often it's helpful to be able to handle more than one thing at a time. This is true when writing programs too. A grocery list is a collection of things you want to buy. Your backpack is a collection of things you take to school. This idea of dealing with more than one thing at a time is useful in programming, and is called a collection variable.

Common Collection Variables
  • List - a simple list of things, like a grocery list
  • Dictionary - a collection of things that has a way to find them. The contact list in your phone is like a Dictionary. You find the person by their name, and that gives you everything else; phone number, email address, picture, etc.
  • Set - just like a list, but there can only be one of a particular thing. Sets are handy when you need a list of unique things, one of each.
Collection Examples

Here we're creating a List variable called "grades", and assigning a list of grades to it. We're also creating a Dictionary called "people" and assigning to it a simple address book with two people in it. And lastly a List called "things" and assigning to it a list of different kinds of things.

                        
    grades = [70, 99, 95, 88, 91, 88]
    people = {"Doug": "Brookfield", "Sam": "New Milford"}
    things = [1, 3.25, "George", True, "What?"]
                        
                    
Conditionals
Conditionals

Deciding when to do something is just as important as knowing what to do. In programming decisions are called Conditionals because in general you want to test whether or not a condition is true or not. Depending on that test, you can decide what to do next.

Conditional Example

Programming languages often show conditionals in this form:
if <condition>
    <statement(s)>

If the condition is true, then the statement(s) following it are run by the program.

Conditional Example

In this example we're testing whether or not the variable right_hand_touch_sensor is equal to the String value "on"

                            
    if right_hand_touch_senser == "on":
        turn_right(90_degrees)
        move_forward(100)
                            
                        
Notice how the comparison operator "==" is different from the assignment operator "=" we saw when creating variables.

Conditional Example

In this example we're expanding the conditional to show an if <this> then <that> else <other thing>

                            
    if light_sensor == "on":
        go_forward(100)
    else:
        go_backward(100)
                            
                        
The "else" is part of the same conditional test and allows us to make two choices based on whether the condition is true or false.

Conditional Example

In this example we're testing for multiple conditions, kind of like a multiple choice test you might take in school.

                            
    if color_sensor() == "green":
        set_speed(20)
        go_forward(100)
    elif color_sensor() == "yellow":
        set_speed(10)
        go_forward(100)
    elif color_sensor() == "red":
        set_speed(0)
                            
                        

Loops
Loop Uses

A game program is an example of a giant loop containing many statements. The loop runs as long as the game runs, and inside that loop the game checks the players controller, updates the game world and redraws the screen many times a second.

Loops

When writing a program, often you'll need two kinds of loops. You'll want to repeat program statements a fixed number of times, or you'll want to keep repeating statements until something changes in your program. So loops come in two basic flavors, a counted loop and a conditional loop.

Counted Loop

A counted loop is where you know how many times you want to repeat the statements inside the loop. For example, I want to do something 25 times and that's all.

Counted Loop Example

In this example we're counting from 0 to 24 (total counts = 25) and printing out the calculated value of count * 10

                            
    for count in range(25):
        print count * 10
                            
                        

Conditional Loop

A conditional loop is one that will run forever until some condition is met, which ends the loop. If you're thinking this sounds like an if / then statement, you're right! A conditional loop runs while a condition is true.

Conditional Loop Example

In this example we're starting a loop that will run forever until the value of the Boolean variable done is equal to True. Inside the loop we run the game engine and test whether the statement are_we_done() is True. When that happens we set the done variable to True, which exits the loop.

                            
    done = False
    while done == False:
        run_game_engine()
        if are_we_done() == True:
            done = True
                            
                        

Computer Languages

A computer language is the translation layer between us and the computer; we understand the language and the computer does too. Computer languages exist because spoken languages, like English, are to complex and imprecise to communicate with a computer.

Computer languages have vocabulary, grammar and punctuation, just like spoken languages. This creates the syntax of the language, the structure of printable/readable characters both the programmer and computer agree mean something. The syntax of a computer language is usually much smaller and more precise than a spoken language.

As an example, many computer languages use the '=' character to mean "assignment", or assignment of a value to a variable. We've seen examples of this already in Python.

                            
    state = "New York"
    PI = 3.14159
    is_done = True
                            
                        
Keep in mind that not all computer languages use "=" for assignment, they are free to use other syntax for this.

Here's an example showing how the syntax of a languge is used to eliminate ambiguity. This code uses the assignment syntax "=" to create two variables and give them values. Then we use the comparison operator "==" to make a decision and print one result or another.

                            
    x = 12
    y = 14
    if x == y:
        print "x is equal to y"
    else:
        print "x is not equal to y"
                            
                        
This makes the assignment operator "=" distinct from the comparison operator "=="

Laziness

One of the hallmarks of being a programmer is laziness, we don't like to do anything more than once. For example, loops allow us to execute a set of statements multiple times. This means we only have to write the statements once inside the loop rather than however many times we want to repeat those statements.

Functions

Another way computer languages help us to be lazy is by allowing us to create our own statements, called functions. Creating functions allows us to collect a set of statements, variables, conditionals and loops together in one place so we can use them over and over again without having to rewrite them all the time.

Function Example

For example, suppose we need to generate long strings of repeated characters more than once, and in multiple places in our program. The lazy (ie: smart) programmer creates a function to do this.

                            
    def create_long_string(char, number):
        '''lets build our string'''
        retval = ""
        for x in range(number):
            retval = retval + char
        return retval
                            
                        

Function Example Usage

Now we can use the function create_long_string() we just created in the previous example to build long strings. Here is how we can use that function:

                            
    print create_long_string("*", 20)
    ********************

    dashes = create_long_string("-", 10)
    print dashes
    ----------
                            
                        

How to Program

A simplified view of learning how to write a program in a particular computer language is to learn the syntax and grammar to put together a sequence of statements that does something you want done.

How to Program

Think about it, what is a recipe or set of driving instructions? The first is a set of steps someone performs to cook something. The second is a set of instructions someone follows to get somewhere. These are programs for humans.

How to Program

A computer program is no different. It's just a set of instructions telling the computer how to do something. You just have to learn how to tell the computer what you want done in a way it understands.

How I Learn to Program

The trick I recommend to learn to program is to give yourself a project that interests you. This helps to focus on only what you need to know in order to finish the project, and ignore everything else. Then with that under your belt, take on another project that lets you learn more and builds on what you just learned.

Lastly...

There's one more, secret pillar to learning programming. The four pillars are tools, nothing more. Just like a saw, or a hammer, or a nail. Knowing how to use the tools together to build something you want is the real secret.