Sunday, July 24, 2016

Variables


Raspberry PI is a computer. Computers have memory. This is where the program (code) is stored as well as the data that it uses (strings, integers, float numbers etc.). You can try to imagine computer's memory as (nearly) endless cabinet with drawers. Each drawer has its unique number which is called 'memory address'. In those drawers computer stores data and code we write.

A variable is a name that will point to a string or number that is stored somewhere in the depths of computer's memory (one of those drawers). Consider this:

>>> name1 = 'Alice'
>>> print name1
Alice
>>>

NOTE!
If you are using Python 3, use:

>>> name1 = 'Alice'
>>> print(name1)
Alice
>>>


The equality sign = assigns string 'Alice' to a variable name. So now, a variable is stored in of of those drawers but you (programmer) don't have to know the drawer address (number). You use variable with the name name1 and computer knows which drawer to look into to pull out the string 'Alice' from.

>>> age = 10
>>> print age
10
>>> age = age +5
>>> print age
15
>>> 

NOTE!
If you are using Python 3, use: 
>>> age = 10
>>> print(age)
10
>>> age = age +5
>>> print(age)
15
>>> 

First the variable age points to the number 10 (again kept in this magical computer drawer with a particular address). Then the program assigns something else to the same variable age: it is a current value of what age points to (10) and adds (+ operator) number 5 to it.

age = age + 1, could be translated into: 

In the drawer labeled age is number 5. Take 5 out and replace with 6 (5+1). Put it back in the drawer labeled age. Now, if you read what's in the drawer labeled age, you will find number 6 there.

Problem Solving 

What is going to be the final value of the variable apples when this code runs?
>>> apples = 7
>>> apples = apples - 5
>>> apples = apples * 4
>>> 

Run this code on your own adding print apples as the last expression and see if you were right!  

Now, write a code that counts the number of minutes in a week. Use a few variables to create this code. Use variable for days, hours, and minutes.