Variables, Expressions and Statements

Variables

Variables act as “storage locations” for data in a program. They are a way of naming information for later usage. Each variable has a name; an example variable name we will use is myLuckyNumber.

For example, the Python statement

myLuckyNumber = 13

stores the value 13 in the variable myLuckyNumber. Then, anywhere you write the variable name myLuckyNumber again, Python retrieves the stored value.

Below, there is a short example of using variables. It has more than one line of instructions. Python executes the first line, then the second line, and so forth, until it reaches the last line.

Variables First Example

Look at the 5 lines of the program in order, and how they correspond to the output. As you can see, myLuckyNumber keeps its value of 13 for the first two print statements, then its value is changed to 7. We also introduced the plus operator (+) above, which adds two numbers together. Similarly, there are operators for subtraction (-), multiplication (*), and division (/). We’ll return to these in a later lesson.

Expressions

Variables/values (operands) and operators, that evaluate to a single value, together make an expression.

These are expressions:

myLuckyNumber = 13 * age 
myName = "roger"
total = 15 / 3

Common Errors

If you ask Python about a variable that has not been defined, you get an error. You will see this error when you misspell a variable’s name, or when you are using a variable that you haven’t created yet.

Variables Exercise 1 – Undefined Error

Variables Exercise 2 – Literal Error

Another error has to do with accidentally swapping the sides of an assignment (=) operator.

We can specify values directly in the programs we write. For example we can specify a number as a literal just by (literally) typing it directly into the program (e.g., 5 or 4.32). In a program, we specify a word, or more generally a string of characters, by enclosing the characters inside quotation marks (e.g., "Hello, World!").

During the execution of a program, the Python interpreter creates an internal representation of literals that are specified in a program (something like 01010111000). 

You can’t directly see the internal representations of values. You can, however, use the print function to see a printed representation in the output window.