Variables and Assignment Statements
Computers must be able to remember and store data. This can be accomplished by creating a variable to house a given value. The assignment operator = is used to associate a variable name with a given value. For example, type the command:
a=3.45
in the command line window. This command assigns the value 3.45 to the variable named a
. Next, type the command:
a
in the command window and hit the enter key. You should see the value contained in the variable a
echoed to the screen. This variable will remember the value 3.45 until it is assigned a different value. To see this, type these two commands:
a=7.32
and then
a
You should see the new value contained in the variable a
echoed to the screen. The new value has "overwritten" the old value. We must be careful since once an old value has been overwritten, it is no longer remembered. The new value is now what is being remembered.
Although we will not discuss arithmetic operations in detail until the next unit, you can at least be equipped with the syntax for basic operations: + (addition), - (subtraction), * (multiplication), / (division)
For example, entering these command sequentially into the command line window:
a=7.32 b=a+5 b
would result in 12.32 being echoed to the screen (just as you would expect from a calculator). The syntax for multiplication works similarly. For example:
a=7 b=a*5 b
would result in 35 being echoed to the screen because the variable b
has been assigned the value a*5
where, at the time of execution, the variable a
contains a value of 7.
After you read, you should be able to execute simple assignment commands using integer and float values in the command window of the Repl.it IDE. Try typing some more of the examples from this web page to convince yourself that a variable has been assigned a specific value.
In programming, we associate names with values so that we can remember and use them later. Recall Example 1. The repeated computation in that algorithm relied on remembering the intermediate sum and the integer to be added to that sum to get the new sum. In expressing the algorithm, we used the names current and sum .
In programming, a name that refers to a value in this fashion is called a variable. When we think of values as data stored somewhere in the computer, we can have a mental image such as the one below for the value 10 stored in the computer and the variable x, which is the name we give to 10. What is most important is to see that there is a binding between x and 10.Whenever the binding in the picture in in effect, the value 10 will be substituted for the variable x in expressions involving x. For example, the value of the arithmetic expression x * 5 would be 50 .
The term variable comes from the fact that values that are bound to variables can change throughout computation. Bindings as shown above are created, and changed by assignment statements. An assignment statement associates the name to the left of the symbol = with the value denoted by the expression on the right of =. The binding in the picture is created using an assignment statement of the form x = 10
. We usually read such an assignment statement as "10 is assigned to x" or "x is set to 10".
If we want to change the value that x refers to, we can use another assignment statement to do that. Suppose we execute x = 25 in the state where x is bound to 10.Then our image becomes as follows:Note that the binding between x and 10 has been broken and a new binding has been established. If we were to evaluate the expression x * 5 in this state, it would yield 125.
Let's execute a few assignment statements using the Python interpreter. In the video below, you see the Python shell displaying "=> None" after the assignment statements. This is unique to the Python shell presented in the video. In most Python programming environments, nothing is displayed after an assignment statement. The difference in behavior stems from version differences between the programming environment used in the video and in the activities, and can be safely ignored.
Choosing variable names
Suppose that we used the variables x
and y
in place of the variables side
and area
in the examples above. Now, if we were to compute some other value for the square that depends on the length of the side, such as the perimeter or length of the diagonal, we would have to remember which of x
and y
, referred to the length of the side because x
and y
are not as descriptive as side
and area
. In choosing variable names, we have to keep in mind that programs are read and maintained by human beings, not only executed by machines.
Note about syntax
In Python, variable identifiers can contain uppercase and lowercase letters, digits (provided they don't start with a digit) and the special character _ (underscore). Although it is legal to use uppercase letters in variable identifiers, we typically do not use them by convention. Variable identifiers are also case-sensitive. For example, side and Side are two different variable identifiers.
There is a collection of words, called reserved words (also known as keywords), in Python that have built-in meanings and therefore cannot be used as variable names. For the list of Python's keywords See 2.3.1 of the Python Language Reference.
Syntax and Semantic Errors
Now that we know how to write arithmetic expressions and assignment statements in Python, we can pause and think about what Python does if we write something that the Python interpreter cannot interpret. Python informs us about such problems by giving an error message. Broadly speaking there are two categories for Python errors:
Syntax errors: These occur when we write Python expressions or statements that are not well-formed according to Python's syntax. For example, if we attempt to write an assignment statement such as 13 = age
, Python gives a syntax error. This is because Python syntax says that for an assignment statement to be well-formed it must contain a variable on the left hand side (LHS) of the assignment operator "=" and a well-formed expression on the right hand side (RHS), and 13 is not a variable.
Semantic errors: These occur when the Python interpreter cannot evaluate expressions or execute statements because they cannot be associated with a "meaning" that the interpreter can use. For example, the expression age + 1
is well-formed but it has a meaning only when age is already bound to a value. If we attempt to evaluate this expression before age is bound to some value by a prior assignment then Python gives a semantic error.
Even though we have used numerical expressions in all of our examples so far, assignments are not confined to numerical types. They could involve expressions built from any defined type. Recall the table that summarizes the basic types in Python.
The following video shows execution of assignment statements involving strings. It also introduces some commonly used operators on strings. For more information see the online documentation. In the video below, you see the Python shell displaying "=> None" after the assignment statements. This is unique to the Python shell presented in the video. In most Python programming environments, nothing is displayed after an assignment statement. The difference in behavior stems from version differences between the programming environment used in the video and in the activities, and can be safely ignored.
Distinguishing Expressions and Assignments
So far in the module, we have been careful to keep the distinction between the terms expression and statement because there is a conceptual difference between them, which is sometimes overlooked. Expressions denote values; they are evaluated to yield a value. On the other hand, statements are commands (instructions) that change the state of the computer. You can think of state here as some representation of computer memory and the binding of variables and values in the memory. In a state where the variable side
is bound to the integer 3, and the variable area
is yet unbound, the value of the expression side + 2
is 5. The assignment statement side = side + 2
, changes the state so that value 5 is bound to side
in the new state. Note that when you type an expression in the Python shell, Python evaluates the expression and you get a value in return. On the other hand, if you type an assignment statement nothing is returned. Assignment statements do not return a value. Try, for example, typing x = 100 + 50
. Python adds 100 to 50, gets the value 150, and binds x to 150. However, we only see the prompt >>> after Python does the assignment. We don't see the change in the state until we inspect the value of x
, by invoking x
,.
What we have learned so far can be summarized as using the Python interpreter to manipulate values of some primitive data types such as integers, real numbers, and character strings by evaluating expressions that involve built-in operators on these types. Assignments statements let us name the values that appear in expressions. While what we have learned so far allows us to do some computations conveniently, they are limited in their generality and re-usability. Next, we introduce functions as a means to make computations more general and reusable.
Source: Carnegie Mellon University, https://oli.cmu.edu/courses/principles-of-computation-with-python-open-free/
This work is licensed under a Creative Commons Attribution 4.0 License.