Variables

A variable is a way of storing data, it’s like a reference that we can come back to at any time. You can create a variable by typing its name on the left hand side, an equal sign, then it’s value on the right side.

name = "John Doe"

This creates a variable named name with a value of John Doe. This variable can now be used anywhere you would like.

name = "John Doe"
print("Hello Mr.", name,"what would you like to have this evening?")

Note

Notice how `name` is not in quotations, that's because we want to reference the variable.

Naming variables

There are some rules that must be followed when naming a variable:

  • Must start with a letter or underscore
  • Cannot start with a number
  • Can only contain alphanumeric characters and underscores (A-z, 0-9, and _)
  • Variable names are case-sensitive (age, Name and name are different variables)
  • A variable name cannot be any of the python keywords

If a variable has multiple words you can use snake_case, which means you separate each word with an underscore (variable_name), because variable names can’t contain spaces.

# Harder to read
firstname = "Betty"
accountid = "253F32"

# Easier to read
first_name = "Betty"
account_id = "253F32"

Data types

You may have noticed that the numbers are created differently than the words, which are created using double quotes. This is because they are different data types. Every variable is of a specific data type, which describes the type of data that is holds inside. The most common data types in python are:

Data typeNameUsageExample
strStringHolds any text"Spam & Eggs"
intIntegerWhole numbers200
floatFloatNumbers with a decimal point99.999
boolBooleanTrue or falseTrue

Strings can be made using both double("") and single (”) quotes.

name = 'Gojo' # str
age = 32 # int
height = 3.6 # float
alive = False # bool

Python is a dynamically typed language, it automatically determines the type of variables automatically determined when running the code, so you don’t have to specify the type of each variable.

Mutability

In python variables are always mutable, meaning they can be reassigned to a new value. The new value may also be of a different data type than the previous value.

count = 1
count = "2"
count = False