Variables and operations
Variables are simply values that are allocated somewhere in the memory of our computer. They are similar to variables in mathematics. They can be anything: text, integers, or floats (a number with precision after the decimal point, such as 2.33).
To create a new variable, you only need to write this:
x = 2
In this case, we have named a variable x
and set its value to 2
.
As in mathematics, you can perform some operations on these variables. The most common operations are addition, subtraction, multiplication, and division. The way to write them in Python is like this:
x = x + 5 #x += 5
x = x - 3 #x -= 3
x = x * 2.5 #x *= 2.5
x = x / 3 #x /= 3
If you look at it for the first time, it doesn't make much sense—how can we write that x = x + 5
?
In Python, and in most code, the "=" notation doesn't mean the two terms are equal. It means that we associate the new x
value with the value of the old x
, plus 5. It is crucial to understand that this is not an equation, but rather the creation of a new variable with the same name as the previous one.
You can also write these operations as shown on the right side, in the comments. You'll usually see them written in this way, since it's more space efficient.
You can also perform these operations on other variables, for example:
y = 3
x += y
print(x)
Here, we created a new variable y
and set it to 3
. Then, we added it to our existing x
. Also, x
will be displayed when you run this code.
So, what does x
turn out to be after all these operations? If you run the code, you'll get this:
6.333333333333334
If you calculate these operations by hand, you will see that x
does indeed equal 6.33
.
Exercise
Try to find a way to raise one number to the power of another.
Hint: Try using the pow()
built-in function for Python.
The solution is provided in the Chapter 03/Variables/homework.py
file on the GitHub page.