Skip to content

BasicProgramming

Gregory McIntyre edited this page Nov 7, 2013 · 4 revisions

(Mostly stolen from Lucy Bain. <3)

  • Variables
  • Procedural execution
  • Basic types of values (integer, string, boolean)
  • Arithmetic (integers)
  • String manipulation (strings)
  • Logic (booleans)
  • Groups of values (arrays)
  • Conditional statements (if)
  • Repeated statements (loops)
  • Re-using code (functions)
  • Varying re-used code (parameters)
  • Advanced kinds of values

Variables

Variables are like boxes with labels on them and something inside. If you ask me "what's your favorite colour?" you make a box in your head labelled "Lucy's favorite colour." Once I tell you "purple" you can fill in that box.

  • What's your favorite colour? purple
  • How tall are you? 165.5
  • Are you Australian? No

Variables in code work the same way. For a computer we can write it like this:

fav_colour = 'purple'
height = 165.5
australian_citizen = false

The equals sign does not mean the same thing as it does in maths! It means "put the value on the right into the box on the left".

There are different types of values. In the example above, 'purple' is how we write a string (any arbitrary piece of text which is a series of letters). 165.5 is a number. false is a boolean value.

See how "purple" has those quotes around it? We're going to come back to that in a later lesson, but just for now… computers "think" in variables, so a computer will assume a normal word (like "height" above) that doesn't have quotes around it is a variable. To tell the computer a word is a word and not a variable, we put quotes around it.

Lucy is the concept of who I am. Using this name makes it easier to reference a larger, more complex thing (like who I am!).

x = 2
y = true
z = 'hello'

What's the value of _?

That's not great, since there's no easy way to remember what x means. Why x? Why not a? Or hrumph? Naming variables is an important part of programming. We try to name things so it's easy to understand what value they hold.

fav_colour = 'purple'
male = false
height = 165

What's the value of ___?

Ok, but what if something changes? Maybe I wake up one day and my favorite colour is now green. Or I suddenly have a growth spurt and put on a couple more cms. That's completely OK! Variables are called "variables" because they can "vary" i.e. "change". They are not required to stay the same; in fact, they usually change.

fav_colour = 'purple'
fav_colour = 'green'
fav_colour = 'yellow'

What's the value of fav_colour?

Nice! So now we know that variables hold values (or, if we think back to nouns, represent concepts) and those values can change. Now we'll try to mix it up a bit.

joe_height = 170
sarah_height = 160
nick_height = sarah_height

Procedural execution

Programs run from top to bottom. Each line of code is an "instruction" that instructs the computer to do something. We call this "procedural" programming, because it is instructing the computer to follow a procedure.

A recipe for a cake as a "Method" section that instructs you on the set of steps you need to follow in order to bake a cake. When you write a program, you are writing a recipe for the computer to follow, step by step, in order, to do something you want it to do. Instead of baking a cake, however, it might be "send a web page to a web browser" or "send an email containing all the right content to the right person" or "draw the next frame of animation".

Here is a brief method for making a cake:

  1. mix dry ingredients
  2. add wet ingredients
  3. mix until there are no lumps
  4. bake for 20 minutes
  5. serve with joy

For serving a web page, the instructions might be:

  1. look at the address (URL)
  2. look at the files on the web server's disk
  3. open the matching file
  4. send the content of the file back to the waiting web browser with joy

Basic types of values (integer, string, boolean)

Integers are numbers with no decimal places. They can be zero or negative too.

joe_height = 170

(If you want decimal places, there is a separate type of value called a "float" to handle that. Usually you can get away with just integers though.)

Strings are sequences of letters, numbers, punctuation marks or spaces, that are often used to represent text.

fav_colour = 'purple'

There are only two boolean values: true and false. They are used in logic expressions like:

australian_citizen = false

Arithmetic (integers)

If you've used a calculator, you know there are operations you can apply to numbers to calculate new values.

x = 3
y = 5
z = x*y

In this statement, we are putting a new value into the box labelled z. The value calculated is x times y. The * symbol is called an "operator" and the values you feed into it in this case are x and y.

In programming, there are many operators you can apply to values to produce new values. Here are all the ones you'll want for integers:

z = x * y
z = x / y
z = x + y
z = x - y

String manipulation (strings)

There are different operators that apply to strings, since "multiplying" them like numbers might not make sense.

greeting = "Hello"
name = "Lucy"
sentence = greeting + " " + name + "."

This sticks the strings together into a sentence.

There are a lot more things we can do to strings besides just sticking them together. Here are a few examples. Instead of using mathematical symbols, they use names like "upcase" which is short for "convert to uppercase". upcase is the operator and sentence is the value that the operator is being applied to.

sentence.upcase
sentence.downcase

Logic (booleans)

Did you ever study logic at school? p implies q, p and ^q, etc. p and q are variables with values, and there are operators here too: "and" and "or" and "not".

p = false
q = true
r = p and q
r = p or q
r = p and not q
cannot_use_medicare = not australian_citizen

Groups of values (arrays)

Arrays are simple rows of boxes for those occasions where you want to store more than one of the same type of thing.

names = ["Larry", "Curly", "Moe"]

There are a bunch of operators that work on arrays. We won't go into all of them. Here're a few.

names.first
names[1]
names.delete("Larry")
sorted_names = names.sort

Conditional statements (if)

Remember baking that cake? Sometimes you only want to do something on some condition.

if fan_forced
  temperature = 220
else
  temperature = 240
end

Only one of these two temperatures will be used, depending on whether fan_forced is true or false.

Repeated statements (loops)

Besides skipping statements sometimes, the other thing you will frequently want to do is repeat a bunch of statements over and over, usually until some condition becomes true.

lumpy = true
while lumpy
  mix_ingredients
  lumpy = check_lumpiness
end

This will execute mix_ingredients over and over again until lumpy is false. Just as many times as it takes!

Re-using code (functions)

In big fancy cake cookbooks there are "subrecipes" in the back for things like icing, that are used in many of the recipes in the book. It would be a bit painful to repeat the icing recipe for every single cake that requires icing in a cake book. So cookbooks put that in the back and just refer to it. "Refer to icing recipe on page 48."

We do exactly the same thing with the sets of instructions we give to the computer. Such subrecipes in programming are called "functions", "procedures", "routines" or "methods" depending on who you ask. "def" in the following example is short for "define".

def make_icing
  mix_icing_ingredients
  add_pink_colour
end

recipe 1 (basic cake):

mix_ingredients
bake
make_icing
ice_cake
serve

recipe 2 (layer cake):

mix_ingredients
bake
mix_ingredients
bake
stack_cake_in_layers
make_icing
ice_cake
serve

There is more we could do to reduce the repetition but we saved ourselves a bit of effort so far.

Varying re-used code (parameters)

If we didn't want every cake to turn out pink, we could give the colour as a parameter to the make_icing function.

def make_icing(colour)
  mix_icing_ingredients
  add_food_dye(colour)
end

recipe 3 (red layer cake):

mix_ingredients
bake
mix_ingredients
bake
stack_cake_in_layers
make_icing("red")
ice_cake
serve

Here we are passing the value "red" to the function make_icing, which is responsible for making the icing, so that it will know what colour we want it. Later on, we can re-use this to make blue icing. You know, for our mermaid cake.

Advanced kinds of values

There are a lot more types of values besides integer, strings, booleans and arrays. There are, in fact, many thousands. But you can do a lot with just those ones.

To give you an idea of the types of values you might encounter as you get past the basics, we will just give you a list of some and you can perhaps imagine what they are for and the sorts of operators that might work on them. Arrays, structs (JSON objects), lookup tables (maps, hashes, dictionaries), nested arrays (an array with arrays in it), trees, graphs, and even totally custom types that you can add to the language to model the problem you're working on at the time. Like Meal, Cake or Dinner.

I shouldn't have written this while hungry, huh?