X/Y
In Python prior to version 3.0
>>>1/2
0
That is, an integer (the number without fractional parts) is divided by another integer, and the fractional part of the result is truncated, leaving only the integral part
Sometimes, this feature is useful, for example, when you do some values that need to be taken on a number of digits, you can use this feature for the end of the loop, but usually you don't.
Then there are two ways to solve this problem:
1) arithmetic with real numbers (numbers containing decimal points) instead of integers
Real numbers are called floating-point numbers in Python (float, or float-point number), as long as one of the numbers participating in the operation is a floating-point, then a floating-point operator, the result of which is also a floating-point number, and does not intercept the decimal part
Such as
>>>1.0/2.0
0.5
>>>1/2.0
0.5
>>>1.2/2
0.5
>>>1/2.
0.5
2) Let Python change the default execution mode for division
You can add the following statement to the program, or execute it in the interpreter:
>>>from_future_import Division
There is another way, if you run Python from the command line, such as on a Linux system, you can use a command switch AH-qnew
Use both of these methods. You can only perform normal division operations.
>>>1/2
0.5
At this point, the single slash is no longer used as an integer, but Python provides another operator to achieve the division of the divide-a double slash:
>>>1//2
0
Even if it is a floating-point number, the slash will perform the divide
>>>1.0/2.0
0
In the version after Pytho3.0
Turns into true division in Python3.0 (regardless of whether any type retains a fractional portion, even if the integer is represented as a floating-point number).
>>> 3/2
1.5
>>> 3/2.0
1.5
>>> 4/2
2.0
>>> 4/2.0
2.0
Python2 and Python3 differences in division operations