Variables – Assignment

In general, variables can be initially given a value (initialization) or have their value updated by using the assignment statement:

<variable name> = <data/value you want to store>

The assignment statement first evaluates the expression on the right and then stores the resulting value in the variable on the left.

For example, when variable x has a value of 6, the assignment statement x = 3*x + 10  determines that 3*x+10 is equal to 28 and then gives x the new value of 28.

NOTE: the statement 2 = x is not allowed in programming languages and will cause a syntax error.

Unlike some programming languages, every variable in Python is a reference to an object. This means that all variables store memory locations where the various pieces of data can be found. This is why Python variables do not have to be declared with a specific data type. A Python programmer must be aware of this and be extra careful in managing data in the code. The flexibility of the language can be very useful, but it can also backfire if a programmer is not careful. A mistake with an assignment statement (e.g. assigning an unexpected piece of information to a variable) can cause logical errors, and students will need help identifying such errors.

Example: Storing a visual attribute in a variable

The following example shows how variables are used. In this case, the variable eyeSize allows us to control the size of both eyes by changing the value at one place:

http://www.khanacademy.org/cs/spin-off-of-intro-to-variables/2604809751

An extension of this example would be to have students think about how to use variables to change the size of the mouth.