Numbers & operators · 数字与运算符
Two kinds of number
- An integer (
int) is a whole number, like7or-3. - A float is a number with a decimal point, like
2.5. - Division with
/always gives a float, even4 / 2→2.0.
两种数字
- 整数(
int)是没有小数的数,例如7或-3。 - 浮点数(
float)是带小数点的数,例如2.5。 - 用
/做除法总是得到浮点数,连4 / 2也会得到2.0。
Add, subtract, multiply, divide
+adds,-subtracts,*multiplies,/divides.- You can use them with variables or with plain numbers.
- Spaces around operators are optional but make code easier to read.
加、减、乘、除
+加,-减,*乘,/除。- 你可以对变量使用它们,也可以直接对数字使用。
- 运算符两边的空格可有可无,但加上会让代码更易读。
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
Whole-number division, remainder, powers
//divides and keeps only the whole part (floor division).%gives the remainder (called modulo).**raises to a power:2 ** 3is 2×2×2.
整除、求余、乘方
//做除法,只保留整数部分(向下取整,floor division)。%求余数(叫作取模,modulo)。**表示乘方:2 ** 3就是 2×2×2。
print(7 // 2)
print(7 % 2)
print(2 ** 5)
Order of operations
- Python does
**first, then*///%, then+-. - This is the same order you use in maths.
- Use parentheses
(...)to change the order.
运算顺序
- Python 先算
**,再算*///%,最后算+-。 - 这和你在数学里用的顺序一样。
- 用括号
(...)来改变运算顺序。
print(2 + 3 * 4)
print((2 + 3) * 4)
Common mistakes
/always gives a float (4 / 2is2.0); use//when you want a whole number.- Power is
**, not^. "3" + "4"joins text into"34"— it does not add to7.
常见错误
/总是得到浮点数(4 / 2是2.0);想要整数用//。- 乘方是
**,不是^。 "3" + "4"是把文本拼成"34",不会得到7。
Now you try
- Store each answer in the variable named in the task.
- Press Check answer to test your code.
现在轮到你
- 把每个答案存进任务里指定的变量。
- 按检查答案来测试你的代码。
Order of operations · 运算顺序
Python evaluates × and ÷ before + and −, left to right. · Python 先算 × 和 ÷,再算 + 和 −,从左到右。
Set · 集合 length to · 到 8 and width to · 到 5. Then store their product in a variable called area. · 把 length 设为 8,width 设为 5。然后把它们的乘积存进变量 area。
Click Run to see the output here. · 点击“运行”查看此处输出。
You share 17 sweets among 5 children. Store how many each child gets in each (use //), and how many are left over in · 入 left (use %). · 把 17 颗糖分给 5 个小孩。把每人分到的数量存进 each(用 //),把剩下的数量存进 left(用 %)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Store 3 ** 2 + 1 in · 入 result. Then use parentheses to store (3 + 1) ** 2 in · 入 grouped. · 把 3 ** 2 + 1 的结果存进 result。再用括号把 (3 + 1) ** 2 的结果存进 grouped。
Click Run to see the output here. · 点击“运行”查看此处输出。
celsius is 37. Store the temperature in Fahrenheit in fahrenheit, using the formula celsius × 9 ÷ 5 + 32. · celsius 是 37。用公式 摄氏度 × 9 ÷ 5 + 32,把华氏温度存进 fahrenheit。
Click Run to see the output here. · 点击“运行”查看此处输出。