Xtralien Scientific Python: Variables

 

Variables are the way that you store values in Python, among other programming languages. Another name for a variable is symbol. Variable assignment is as simple as in mathematics. You store a value in a variable by using the equals symbol (=).

x=1
y=x+2

Your first Assignment

Due to Python's resembelence to mathematics, assigning values to variables is as simple as writing an equation.

x = 1

We can test this by printing the value of x.

print(x)

This would print the value of x to the console, which in this case would be 1.

Assigning a result

Assigning a static value isn't useful by itself, so in most cases you will want to store a result in a variable. In this example we will store the result of a simple addition.

z = 1 + 1

This will run the addition and then store the result inside the variable z for later use. We can check this by printing z.

print(z)

This will print 2, which is the result of the addition.

Using Variables

As seen before, variables can be used as arguments to functions (more on this later in the functions section). The method by which we use variables is by simply stating them where we wish to use them.

In the above case we provided z as an argument to the print function. In the following example we use the previously defined variable x to create a new variable, y.

y = x * 2

This will multiply the value stored in the variable x by 2 and store the result in the variable y.

Updating a value

In Python the assignment of a value to a variable happens after the right-hand-side (RHS) of the assignment is executed. This means that you can update the value of a variable by using the variable in the update.

In the example below we add 1 to the value of z, which we previously defined as 2.

z = z + 1

This will run z + 1 and then assign that result to the variable z, overwriting the previous value.

In-place updates

Because these types of updates to variables are common, there is a shorthand for them in Python. These are called in-place updates and they use a modifier on the assignment operator (=). An example of this is a replication of the above example.

z += 1

This example will perform exactly as the above example, modifying the value of z by adding 1 and storing the result.