Memory & Variables
Exercises
exercises2_solutions.pptx | |
File Size: | 208 kb |
File Type: | pptx |
Storing Values in Variables
A variable is like a box in the computer’s memory where you can store a single value. If you want to use the result of an evaluated expression later in your program, you can save it inside a variable.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment statement consists of a variable name, an equal sign (called the assignment operator), and the value to be stored. If you enter the assignment statement spam = 42, then a variable named spam will have the integer value 42 stored in it.
Think of a variable as a labeled box that a value is placed in, as in the figure below:
Think of a variable as a labeled box that a value is placed in, as in the figure below:
For example, enter the following into the interactive shell:
A variable is initialized (or created) the first time a value is stored in it ➊.
After that, you can use it in expressions with other variables and values ➋.
When a variable is assigned a new value ➌, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the end of the example.
This is called overwriting the variable. Enter the following code into the interactive shell to try overwriting a string:
After that, you can use it in expressions with other variables and values ➋.
When a variable is assigned a new value ➌, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the end of the example.
This is called overwriting the variable. Enter the following code into the interactive shell to try overwriting a string:
Just like the box below the spam variable in this example stores 'Hello' until you replace it with 'Goodbye'. When a new value is assigned to a variable, the old one is forgotten:
Variable Names
You can name a variable anything as long as it obeys the following three rules:
- It can be only one word.
- It can use only letters, numbers, and the underscore (_) character.
- It can’t begin with a number.
The table below has examples of valid and invalid variable names:
NOTE: variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four different variables. ItIt is a Python convention to start your variables with a lowercase letter.