Variables · 变量
A box with a name
- A variable is a named box that holds a value.
- You put a value in the box, then use the name later.
- The value can be a number or a string.
有名字的盒子
- 变量(variable)是一个有名字的盒子,用来存放一个值。
- 你把值放进盒子,稍后用名字来使用它。
- 这个值可以是数字,也可以是字符串。
Make a variable
- Write
name = valueto store a value. - The name is on the left. The value is on the right.
=means "store this value", not "is equal to".
创建变量
- 写
name = value来存放一个值。 - 名字在左边,值在右边。
=的意思是"把这个值存进去",而不是"等于"。
city = "Paris"
print(city)
Naming rules
- Use letters, digits, and the underscore
_. - A name cannot start with a digit and cannot have spaces.
- Names are case-sensitive:
scoreandScoreare different. - Pick clear names like
ageortotal_score.
命名规则
- 可以用字母、数字和下划线
_。 - 名字不能以数字开头,也不能有空格。
- 名字区分大小写:
score和Score是不同的。 - 选清楚的名字,例如
age或total_score。
Change a variable
- You can store a new value at any time.
- The new value replaces the old one.
- The name still points to one value — the latest one.
修改变量
- 你可以随时存入一个新的值。
- 新的值会替换旧的值。
- 名字始终指向一个值 —— 最新的那个。
A variable is a labelled box · 变量是一个带名字的盒子
Step through the program. Each line stores a value in a named box; reassigning count overwrites its box. One name, one current value. · 逐行运行程序。每行都把一个值放进带名字的盒子;重新赋值 count 会覆盖它原来的盒子。一个名字,只保存一个当前值。
count = 1
count = 2
print(count)
Constants
- A constant is a value that should not change.
- Python has no special keyword for it.
- By convention, we write constant names in
UPPERCASE.
常量
- 常量(constant)是一个不应该改变的值。
- Python 没有专门的关键字来表示它。
- 按照惯例,我们把常量的名字写成
UPPERCASE(全大写)。
PI = 3.14159
print(PI)
Common mistakes
- Use
=to store a value: the name goes on the left, the value on the right. - Use a variable only after you have given it a value, or you get a NameError.
- Names cannot start with a number or contain spaces.
常见错误
- 用
=存值:名字在左,值在右。 - 先给变量赋值再使用,否则会得到 NameError。
- 名字不能以数字开头,也不能包含空格。
Now you try
- Use a variable for each task below.
- Press Check answer to test your code.
现在轮到你
- 下面每个任务都要用到变量。
- 按检查答案来测试你的代码。
Create a variable called age and store the number 15 in it. · 创建一个名为 age 的变量,把数字 15 存进去。
Click Run to see the output here. · 点击“运行”查看此处输出。
The variable color starts as "red". Reassign it so that it becomes "blue". · 变量 color 一开始是 "red"。重新赋值,让它变成 "blue"。
Click Run to see the output here. · 点击“运行”查看此处输出。
Constants are written in UPPERCASE by convention. Create a constant MAX_SCORE and set it to 100. · 常量按惯例写成全大写。创建一个常量 MAX_SCORE,并把它设为 100。
Click Run to see the output here. · 点击“运行”查看此处输出。
a is 1 and b is 2. Swap them, so a becomes 2 and b becomes 1, without typing the numbers 1 or · 或 2 again. (Tip: a third variable can hold one value for a moment.) · a 是 1,b 是 2。把它们交换,让 a 变成 2、b 变成 1,而且不要再输入数字 1 或 2。(提示:可以用第三个变量暂时保存一个值。)
Click Run to see the output here. · 点击“运行”查看此处输出。