Variables, constants & data types · 变量、常量与数据类型
A variable is a named box
- A variable is a name that stores a value.
- You put a value in with
=— this is called assignment. - Use a clear name so the program is easy to read.
变量是一个有名字的盒子
- 变量(variable)是一个用来存值的名字。
- 用
=把值放进去 —— 这叫做赋值(assignment)。 - 用清晰的名字,程序才好读懂。
age = 15
price = 2.50
name = "Ada"
print(age, price, name)
Variables as named boxes · 变量是有名字的盒子
Each · 每个 = puts a value into a named box you can use later. · 每个 = 把一个值放进一个有名字的盒子,之后可以使用。
The five data types
- IGCSE uses five basic data types:
- integer (whole number) → Python
int; real (decimal) →float. - char (one letter), string (text) →
str; Boolean (True/False) →bool.
五种数据类型
- IGCSE 用五种基本数据类型(data type):
- 整数(integer)→ Python
int;实数(real,小数)→float。 - 字符(char,一个字母)、字符串(string,文本)→
str;布尔(Boolean,True/False)→bool。
score = 42 # integer 整数
height = 1.75 # real 实数
grade = "A" # char 字符
town = "Cairo" # string 字符串
passed = True # Boolean 布尔
Constants stay the same
- A constant is a value that never changes while the program runs.
- Python has no special keyword, so we write constants in
CAPITALS. - This warns other readers: do not change me.
常量保持不变
- 常量(constant)是程序运行时永远不变的值。
- Python 没有专门的关键字,所以我们把常量名写成
大写字母。 - 这是在提醒其他读者:不要改我。
PI = 3.14159
VAT_RATE = 0.20
print(PI)
Changing between types
input()gives a string, so convert it when you need a number.int(x)makes a whole number;float(x)a decimal;str(x)makes text.
在类型之间转换
input()返回字符串,所以需要数字时要转换。int(x)得到整数;float(x)得到小数;str(x)得到文本。
n = int("5")
print(n + 1) # 6
print("Total: " + str(n)) # Total: 5
In the exam: DECLARE and CONSTANT
- Pseudocode names a type with
DECLARE, and fixes a value withCONSTANT.
在考试里:DECLARE 与 CONSTANT
- 伪代码用
DECLARE声明类型,用CONSTANT固定一个值。
DECLARE Age : INTEGER
Age ← 15
CONSTANT Pi ← 3.14
Common mistakes
- Give a variable a value before you use it.
- A constant is a value you do not change — name it clearly.
- Keep the right type: numbers for maths, strings for text.
常见错误
- 先给变量赋值再使用。
- 常量是不会改变的值——给它清晰的名字。
- 用对类型:数字用于运算,字符串用于文本。
Now you try
- Make variables and do a little maths with them.
- Press Check answer to test your code.
现在轮到你
- 创建变量,并用它们做一点数学运算。
- 按检查答案来测试你的代码。
The variables width and height are set for you. Work out the rectangle's area · 面积 (width × height) and store it in a variable called area. · 变量 width 和 height 已为你设好。算出矩形的面积(width × height),并存进一个名为 area 的变量。
Click Run to see the output here. · 点击“运行”查看此处输出。
price is a real · 实数 number and quantity is an integer. Work out the total cost (price × quantity). · price 是一个实数,quantity 是一个整数。算出总价 total(price × quantity)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a whole number with input(), convert it with int(...), then print the number plus 3. For input 7, the output should be 10. · 用 input() 读取一个整数,用 int(...) 转换,然后打印这个数加 3 的结果。当输入为 7 时,应输出 10。
Click Run to see the output here. · 点击“运行”查看此处输出。