In this lesson, we're going to learn about variables. What is a variable? A name or space that stores a value or data is called a variable because it can change at any time.
Variables point to integer values
Okay, on my desk I have a clock, a lighter, a toothbrush, a pen, and the paper cup I've been using to drink water for a week. How much is my watch worth? Five dollars? No, let's just say that my watch is worth 100,000 dollars.
Now let's say someone wants to buy my watch. How much is my watch worth? It's called value. If I ask for a million dollars, it's a million dollar watch.
Let's programmatically express the value of the watch
>>> watch = 100000
This is how I write that my watch is worth 100,000 won.
Now, let's express the lighter the same way
>>> lighter = 300
The lighter costs 300 won.
Using variables to calculate numbers
So, how much would you have to give me to buy a watch and a lighter from me? If you want to buy a watch, you'll have to give me a million won instead of 100,000 won, so you'll have to increase the value of the watch.
>>> watch = 1000000
The watch that cost 100,000 won is now worth 1 million won, so what's the total?
Some of you do the math by eye, right? Let's ask the computer to do it for us.
>>> watch + lighter 1000300
Wow, the smart computer did the math in a flash. You can put a value in a variable multiple times.
Calculating the value of a variable and assigning it to the same variable again
You want to sell your watch to buy a gaming console. What is the 15% discount on a watch that costs 1 million won?
>>> 1000000 * 0.85 850000.0
(Of course, you could also calculate it as 1000000 - 1000000 * 0.15
or 1000000 * (1 - 0.15)
, but we'll stick with the above).
Similarly, if you wanted to discount the value pointed to by some variable by 15%, you could probably represent it with code like this
>>> price = 5000 >>> price = price * 0.85 >>> price 4250.0
The above sentence in the form variable = variable * value
can also be abbreviated to variable *= value
>>> price = 5000 >>> price *= 0.85 >>> price 4250.0
Variables that point to strings
Variables can contain letters as well as numbers.
>>> a = 'pig'
This
tells the variable a to contain the string 'pig'
(multiple letters), so a
equals '
pig'. Notice the quotation marks around '
pig'. Without the quotation
marks, it would be mistaken for the variable pig. The quotation
marks are
used to say “pig is a string”. Now, let's put the string 'dad' in a variable called b.
>>> b = 'dad'
That's easy, right? Now let's try concatenating strings together
>>> a + b pigdad
We used the same method as when we added the watch and lighter values, and the strings were joined together. Isn't that fun? Not fun? Well, let's try something a little more fun.
>>> a + ' ' + b pig dad
Here, we've created a
string called 'pig dad'
by concatenating a
variable called a
with ' '
(one space character) and a variable called b.
Does that make sense?