By the end of this lesson, we'll understand how variables work, as well as different types of data.

Variables

Defining variables

Computer science is closely related to mathematics, and the fundamental ideas of comp sci are closely interwoven with fundamental ideas in mathematics. Algebra, in particular, is also present in programming, in a similar way.

$$ 3 + 4 = 7 $$

We can easily replace the 7 with the pronumeral x in algebra, to get: 3 + 4 = x. Moving forward, whenever we see the letter x, we can replace it with the result of the addition (7). This should come pretty naturally to an algebra student.

In programming, we can do the same thing but the constraints are different. First of all, if we are changing the value of a pronumeral (called a variable), the variable must be isolated and on the left half side. Here are some bad variable definitions which will fail:

# BAD
2 + x = 7  # (variable not isolated)
5 = x      # (variable name must be on left hand side)

# GOOD
x = 5

Another change is that we are no longer restrained to use single letter pronumerals like "x" and "y". We can call variables anything we like, as long as they're consisted of the characters (a-z, A-Z, _, 0-9). Also, the variable name cannot begin with a number.

# GOOD
hello = 6
hello_variables_1 = 8

# BAD
1a = 3   # (name cannot begin with digit)
a-b = 7  # (name cannot contain a -)

Seeing the value of a variable

This language isn't very useful for us at the moment though. For instance, if we try using Python to calculate 2 + 2 (which equals 5), we can create a new variable:

result = 2 + 2

But we don't know the value of result yet! We can show the value of result with the function print. We'll dive deeper into functions later, but for now, here is all you need to know about print: