Integers & Floats
整数与浮点数
Python's two numeric types — int for whole numbers, float for fractions — look similar but behave differently. Knowing when each one shows up will save you a lot of confusing bugs.
Two kinds of numbers
In Python, 3 and 3.0 are not the same value. The
first is an int (integer); the second is a float
(floating-point number). You can ask Python which is which:
The rule for arithmetic: if all operands are int, the result is
int. As soon as one float sneaks in, the whole
expression "promotes" to float.
Operators you'll use every week
+addition-subtraction*multiplication/true division — always returns afloat//floor division — drops the remainder, returns the smaller type%modulo — the remainder**exponent —2 ** 10is 1024
Converting between types
The functions int(), float(), and str()
take a value and return a new value of the requested type. They do
not change the original.
Check yourself
What does this print? x = 7 / 2 → print(type(x))
Check yourself
`x = int(3.9)` — what is x?
The exercise in WolfCode
Open 02-types-int-float.py. Four variables are set to
None — replace each with the correct expression. The tests
check both the value and the type.