Variables and Assignments
| English | Chinese | Pinyin |
|---|---|---|
| variables | 变量 | biàn liàng |
| named reference | 命名引用 | mìng míng yǐn yòng |
| value | 值 | zhí |
| memory | 内存 | nèi cún |
| assignment | 赋值 | fù zhí |
| update | 更新 | gēng xīn |
| data types | 数据类型 | shù jù lèi xíng |
| number | 数字 | shù zì |
| string | 字符串 | zì fú chuàn |
| Boolean | 布尔值 | bù ěr zhí |
| executes | 执行 | zhí xíng |
A variable is a labelled box
- A running program needs to remember information — it uses variables 变量.
- A variable is a named reference 命名引用 that stores a value 值 in the computer's memory 内存.
- Picture a labelled box: the label is the name, the box holds one value at a time.
- Give it a clear name like
totalScore, not a vaguex.
A variable is best described as:
The name is the label; the box holds the current value.
In score ← 10, the arrow means score ______ the value 10.
Assignment stores the right-hand value into the left-hand name.
Assigning a new value to a variable throws away its old value.
A variable holds one value at a time; the new one overwrites the old.
Assignment
- An assignment 赋值 puts a value into a variable. In AP pseudocode: $\text{score} \leftarrow 10$.
- The arrow $\leftarrow$ means "gets the value", so
scorenow holds $10$. - An assignment can also update 更新 a variable with a new value — the old value is thrown away.
- The right side is worked out first, then stored in the name on the left.
A variable is a labelled box
Each assignment works out the right side and stores it in a named box; reassigning the same name overwrites it. Step through and watch each box take its value.
Match each value to its data type.
Numbers, strings, and Booleans are the basic data types here.
Data types
- A variable can hold different kinds of value, called data types 数据类型:
- a number 数字, such as $7$ or $3.5$;
- a string 字符串, a piece of text such as "cat";
- a Boolean 布尔值, which is either true or false.
total ← 5, then total ← total + 3, then total ← total × 2. What is total?
5 → 8 → 16, each line using the previous value.
Why prefer the name totalScore over x?
Readable names help you and your teammates understand the code.
Tracing changes
- As a program executes 执行, the value of a variable can change.
- Tracing these changes by hand helps you understand the program.
Trace total. $\text{total} \leftarrow 5$ stores 5. $\text{total} \leftarrow \text{total} + 3$ reads 5, adds 3, stores 8. $\text{total} \leftarrow \text{total} \times 2$ reads 8, stores 16. So total ends as 16 — each line uses the value from the line before.
A variable is a named box that stores one value in memory. An assignment ($\leftarrow$) works out the right side, then stores it in the name on the left, overwriting the old value. Variables hold data types — number, string, Boolean — and their values change as the program executes.