Variables

As in algebra, we will use variables in Python to store values for later use in your code. Let’s create a variable named x that stores the integer 7, which is the variable’s value:

x = 7

This is a statement. A statement is a block of code that tells your computer to do something specific. The preceding statement creates x and uses the assignment symbol (=) to give x a value. The entire statement is an assignment statement that we read as “x is assigned the value 7.” Most statements stop at the end of the line, though it’s possible for statements to span more than one line. The following statement creates the variable y and assigns to it the value 3:

y = 3

You can use the values of x and y in mathematical expressions:

x + y

The + symbol is the addition operator. It’s a binary operator because it has two operands (in this case, the variables x and y) on which it performs its operation.

You’ll often save calculation results for later use. The following assignment statement adds the values of variables x and y and assigns the result to the variable total, which we then display:

total = x + y
print(total)

The first line of code reads, “total is assigned the value of x + y.” The = symbol is not an operator. The right side of the = symbol always executes first, then the result is assigned to the variable on the symbol’s left side. The second line of code is a statement that tells your computer to display a value.

A variable name, such as x, is an identifier. Each identifier may consist of letters, digits and underscores (_) but may not begin with a digit. Python is case sensitive, so number and Number are different identifiers because one begins with a lowercase letter and the other begins with an uppercase letter.

Each value in Python has a type that indicates the kind of data the value represents. You can view a value’s type, as in:

type(x)
type(10.5)

The variable x contains the integer value 7 (from line 1), so Python displays int (short for integer). The value 10.5 is a floating-point number (that is, a number with a decimal point), so Python displays float. The type() statement displays the type of a value.