So far, we have been using Python only as a large calculator. Now, we want to make variables, which can store the results of our math. We can assign a name and a value to a variable, and then manipulate it.
Try the following in the console:
x = 2
x = x + 2
x
You will see the following output:
Try the following in the console:
x = 2
x = x + 2
x
You will see the following output:
Keep your eye on the variable explorer above the console while you input each line. Notice how the value of x is updated. First, we create a variable and assign it the value 2. Next, we say x gets itself (2) + 2, so now x = 4. Finally, typing x displays the value of x on the console.
Now let's use variables to calculate something useful! Let's say we have a right-angle triangle with legs length 4 and 6. We want to find the length of the hypotenuse using the Pythagorean theorem. Let's do that using the math module and variables.
import math #
a = 6
b = 4
c = math.sqrt(a**2 + b**2)
c
You should see the following. Note that c has the value 7.2 in the variable explorer as well.
Now let's use variables to calculate something useful! Let's say we have a right-angle triangle with legs length 4 and 6. We want to find the length of the hypotenuse using the Pythagorean theorem. Let's do that using the math module and variables.
import math #
a = 6
b = 4
c = math.sqrt(a**2 + b**2)
c
You should see the following. Note that c has the value 7.2 in the variable explorer as well.
Quick note: notice the text after the # symbol is greyed out? That's called a comment. Comments are ignored entirely by Python, and are only there to help the humans reading the code. When you write code whose functionality isn't immediately clear, adding a comment or two can help a lot for the next person who has to read it.
Play around more with variables. Once you're comfortable, let's move on to the next tutorial where we will use a new module to work with matrices.
Play around more with variables. Once you're comfortable, let's move on to the next tutorial where we will use a new module to work with matrices.