3.1. Assigning a Name¶
Understand the concept of a variable.
Assign a value to a variable.
Use assignment in calculations.
Understand the ways that students get assignments wrong.
Reuse variables across different assignment statements.
A computer can associate a name with a value. It does this by creating a variable, which is space in computer memory that can represent a value. An example of a variable is a score in a computer game. The score usually starts at 0 and increases as you play the game. The score can change or vary during the game, which is why we call it a variable. You also associate a name with a value when you enter a new contact name and phone number in your cell phone. When you tell your phone to call “Alexa” it will look up the phone number associated with that name and call it.
Think of a variable as a box that has a label on it and you can store a value in the box. The value can be anything that can be represented on a computer and stored in a computer’s memory. A computer’s memory is only made up of numbers (really, just patterns of voltages, but we can think about them as numbers). Everything that a computer can remember in its memory is translated into these numbers – but don’t worry about how this works right now.
In programming languages, setting a variable’s value is also called assignment. A statement like
a = 4 means that the symbol
a refers to space (in the computer’s memory) that is assigned the value
4. When we use the symbol
a in a program the computer will substitute the value
4. If we later change the value stored at
a, say by doing
a = 7.2 then we say that the variable
a now has the value
7.2 meaning that the value in the box (memory) associated with the name
a is changed to
Click on the right arrow below to play the following video.
3.1.1. Legal Variable Names¶
There are restrictions on what you can use as a variable name.
It must start with a letter (uppercase like
Aor lowercase like
a) or an underscore
It can also contain digits, like
9, just not as the first character
It can’t be a Python keyword such as
while. These have special meaning in Python and are part of the language.
Case does matter. A variable named
resultis not the same as one named
Since you can’t have spaces in a variable name you can either join words together by uppercasing the first letter of each new word like
heightInInches or use underscores between words
height_in_inches. Uppercasing the first letter of each new word is called camel-case or mixed-case.
Discuss topics in this section with classmates.