Variables - an interactive introduction#

Variables are used to store values and other objects. To create a variable, you use the assignment operator, like x = 1.

Variables should be

  • descriptive
  • meaningful
  • helps to re-read the code
  • keywords cannot be used as a name

Values assigned to a variable are

  • information that is stored
  • can be updated

Assigning a value to a variable in steps:

  • We start with name_of_a_variable = <expression>.

  • Python computes the right hand side to obtain a value

  • Then stores it (in the left hand side) as a variable.

You can always replace the value of the variable by using the assignment operator =

Let’s try it. Set x to 1, y to 2, and then calculate something with them, like x*y.

Here’s a bunch of examples to show how to use these to do basic arithmetic

# Assigning some numbers to different variables
# NOTE: This is a comment, it's just to help you understand the code, the computer will ignore it!
num1 = 10
num2 = -3
num3 = 7.41
num4 = -.6
num5 = 7
num6 = 3
num7 = 11.11
# Addition
num1 + num2
7
# Subtraction
num2 - num3
-10.41
# Multiplication
num3 * num4
-4.446
# Division
num4 / num5
-0.08571428571428572
# Exponent (powers)
num5 ** num6
343

What happens if we set a variable to another one? Try doing x = y. Think about what x and y should be, then test whether you’re correct.

What is this output telling us? Think about it. Ask us if you’re unsure!

Now set y to something else, like y = 3. What will x be equal to after doing that? There are two possibilities. Think about them both, then test it. Try to explain to someone else the two possibilities, and what you’ve just learned about how Python treats variables.

Variable names should be descriptive but not too long. Any name made with letters, numbers, and underscores will work if it’s not a reserved Python keyword. Examples are energy, variable7, and very_long_variable_name. Try assigning to a few of your own.

You can make your code clear by choosing good variable names, and also by writing comments. A comment is made by putting text after a hash sign.

# Example of a Python comment

some_variable = 5 # You can put a comment after a statement

# You can add a hash sign before a line
# to temporarily stop it from being evaluated
# when you're trying to debug your code, e.g.:

# another_variable = 10*(some broken code)

There’s also some quick ways to write basic operators, let us demonstrate

# Increment existing variable
num7 += 10 # the same as num7 = num7 + 10
num7
21.11
# Decrement existing variable
num6 -= 2 # the same as num6 = num6 - 2
num6
1
# Multiply & re-assign
num7 *= 5 # the same as num3 = num3*5
num7
105.55