How to Win Friends and Influence Computers

By Andrew Hall - @RealAndrewHall

What is this all about?



  • We will learn about the concepts of programming
  • The concepts will not be specific to a particular programming language
  • It will not try to teach you how to be a programmer.

The aim of this presentation is to improve your knowledge of how programming works




It will contain lies

Basic Programming Concepts

You don't need to be scared!

It's not magic

Programming is a list of instructions for the computer

It is like creating a recipe that the computer follows

Basic Programming Concepts

We will cover the following items:

  • Variables
  • Functions
  • Control Structures and Loops




But first.... A quick exercise

Variables

What are Variables?

Variables are just buckets!

They are a place to store something that you will use later and you can update the contents at any time.

You can store lots of different things in a variable - but basically anything you need to know later on in your code.

Examples of Variables:

  • Results from a database
  • A username
  • The number of apples I own

Variable Code Example

Here we are creating a new variable called reminder and storing the sentence Variables are buckets inside it.

// create the variable and set the contents
var reminder = "Variables are Buckets";
console.log(reminder);
// outputs "Variables are Buckets"

We can recall the contents of this variable or modify the contents at any time:

// modify the contents of the variable
reminder = "Don't eat yellow snow";
console.log(reminder);
// outputs "Don't eat yellow snow"

What else can I put in a variable? - Example

We can store all kinds of things inside a variable - in programming terms, these are called types.

string:
a word or sentence - example: "Hello, I am a string"
integer:
a whole number - example: 546
float or double:
a number with a decimal point - example: 8787.33
array or list:
a list of items - example: green, red, blue
boolean:
true or false - example: true

How do you use variables?

You can use variables in many different ways and this often depends on what type of variable you are using.

//create the variable "reminder" and set contents
var reminder = "Don't eat yellow snow";
console.log("Don't forget - " + reminder);

Using an integer (whole number):

//create the variable "appleCount" and set the value
var appleCount = 4;

//if I eat an apple, I will have one less
appleCount = appleCount - 1;
console.log(appleCount);

Variable Quiz

Guess the Type
What type is a number with decimal places? Float or Double
True or False
A list of items is called an Array? TRUE
What will this output?
var name = "James";
console.log("Hello " + name + " - Nice to meet you");
Hello James - Nice to meet you

Variable Recap

Variables are just like buckets.

You can fill them up, remove things and change their contents just like a bucket.


Functions

Functions are pieces of code that perform some logic and then tell you the outcome of that logic.

Functions are sets of instructions to perform a task.
Example: Putting the bins out:

  • Find Bins
  • Find Gate
  • Open Gate
  • Find Kerb
  • Move Bins to Kerb

Each of these steps could be a function in their own right too - This way we can use the inner functions elsewhere too.

Function Code Example

In the following function, we add the number 4 to the number 8:

//create or declare the function
function add4and8(){
    return 4+8;
}

//call the function and put the value into the returnValue variable
var returnValue = add4and8();
console.log(returnValue); // outputs 12

We can call this function anywhere we want to know the value of 4+8:

//call our function and put the value into the variables
var returnValue = add4and8();		
var fourPlusEight = add4and8();

console.log(returnValue); //outputs 12
console.log(fourPlusEight); //outputs 12

But this isnt very useful! - Exercise

In this example, we can now calculate the value of 4 and 8.
But what if we want to to know the value of 2 other numbers?

For this, we can use arguments. This allows us to send some data to our function and makes our code more reusable

//create our function with 2 arguments
function addTwoNumbers(numberOne, numberTwo){
    return numberOne + numberTwo;
}

//call our function with our arguments
var result = addTwoNumbers(15, 45);
console.log(result); //outputs 60

//call our function with different arguments var result = addTwoNumbers(11, 677); console.log(result); //outputs 688

Real life example

In the real world we use functions where we don't want to duplicate code and where we want to do the same task repeatedly.

//create our function
function calculateVat(amount){
    return amount * 0.2;
}

var totalSaleAmount = 10;
var vatAmount = calculateVat(totalSaleAmount);
console.log(vatAmount);  //outputs 2

var secondSaleAmount = 41.76;
vatAmount = calculateVat(secondSaleAmount);
console.log(vatAmount);  //outputs 8.35

This makes life much easier if the VAT rate changes, as we only have to change the code in one place.

Function Quiz

What is the name of a piece of information that you pass to a function?
An Argument or Parameter
True or False?
A function can take no arguments? True
Why do we break code down into functions?
To increase reusability and maintainability

Function Recap


Functions are used for pieces of code that you will reuse.

If you need to modify that set of code, you only need to change it one place.

You reduce duplication of code and therefore reduce the amount of bugs that could be in that code

This is why functions should be broken down into small pieces

Control Flow

We are now going to discuss how to add some logic and conditions to our applications.

There are many scenarios where we want to have different logic or perform different tasks based on certain conditions.

We are used to these kind of things from everyday life:

  • If today is my birthday, I should eat cake
  • While I am hungry, I should eat food
  • For every letter that arrives in the post, open and read them

If statement

Example: If today is my birthday, then eat cake.
If it's not my birthday, then cry

//define my birthday
var myBirthday = "23rd February";
var todaysDate = "24th February";

//check if the values are the same
if (myBirthday == todaysDate){
    eatCake();
}else{
    cry();
}

Switch

Switch is just a lot of if statements grouped together.

Example: Write out a welcome message based on which day it is

var today = "Wednesday";
var welcomeMessage;

switch(today){
    case "Monday":
        welcomeMessage = "5 days until the weekend :(";
        break;
    case "Tuesday":
        welcomeMessage = "4 days until the weekend";
        break;
    case "Wednesday":
        welcomeMessage = "Yay! Its the middle of the week!";
        break;
    ...
}

console.log(welcomeMessage);

While statement - Exercise

Example: While I am hungry, then eat some food

//define how full we are to start
var stomachPercentage = 70;

//define how to work out if we are hungry
function hungry(){
    if (stomachPercentage<100){
        return true;
    }else{
        return false;
    }
}

//define what happens when we eat food
function eatFood(){
    stomachPercentage = stomachPercentage + 10; //add 10 percent when we eat
}

while (hungry()){
    //how many times will this run?
    eatFood();
}

For statement

Example: For each letter I receive, read the letter

//define list of letters
var letterList = ["Bank Letter", "Postcard from Dave", "Junk"];

//iterate through list of letters and call readLetter function on each letter
for (letter in letterList){
    readLetter(letter);
}

Control Flow and Conditionals Quiz

When you want to check if something is true or false, which conditional should you use?
An if statement
True or False
A switch is very similar to an if statement with lots of conditions TRUE
If you want to loop through a list of items, which statment should you use?
Use a for or while loop to iterate through all of the items

Control Flow and Conditionals Recap

You can use these statements when you want to apply logic to your code or only do certain pieces of functionality in certain cases.

Whether it is checking a condition with an if statement or processing a list of items with a for loop, these control flow statements give your code structure and allow you to apply your business logic to your code.

Recap

In just a short period of time, we have learnt about:

  • Variables - Temporary storage of values that we need later
  • Functions - Isolated pieces of functionality/Actions
  • Control Flow and Conditionals - How we can provide different functionality



ABOUT THOSE LIES....

Questions?

@RealAndrewHall