Notes for division in Python: python Division
The example in this article explains the precautions for division in Python, which is a very important technique and has good reference value for Python program design. The specific analysis is as follows:
The following is an example:
def avg(first, *rest): return (first + sum(rest)) / (1 + len(rest)) # Sample use avg(1, 2) # 1.5 avg(1, 2, 3, 4) # 2.5
The source program is only used to demonstrate the use of variable length parameters. However, in the interpreter of Python 2.7.1, the result I get is different from the result of the annotation.
>>> def avg(first, *rest): ... return (first + sum(rest)) / (1 + len(rest)) ... >>> avg(1, 2) 1 >>> avg(1, 2, 3, 4) 2
Obviously, the data after the decimal point is truncated. I remember that the two integers are separated, and "//" should be an integer. Do you remember wrong?
>>> def avg(first, *rest): ... return (first + sum(rest)) // (1 + len(rest)) # change '/' to '//' ... >>> avg(1, 2) 1 >>> avg(1, 2, 3, 4) 2
I changed "/" to "/", and the result is the same. "//" is indeed an integer, but why is the result of "/" truncated?
I tested the same program in the interpreter 3.4.1 and got the expected result:
>>> def avg(first, *rest): ... return (first + sum(rest)) / (1 + len(rest)) ... >>> avg(1, 2) 1.5 >>> avg(1, 2, 3, 4) 2.5 >>> def avg(first, *rest): ... return (first + sum(rest)) // (1 + len(rest)) # change '/' to '//' ... >>> avg(1, 2) 1 >>> avg(1, 2, 3, 4) 2
We can see that in the interpreter 3.4.1, the result of "/" retains the decimal places, while "//" is the result after the integer.
After searching, I found this question on stackoverflow: How does one force division in Python to result in a floating point number? Note that this is for version 2.x. This problem does not exist in version 3.x.
The first two solutions are good:
Method 1:
>>> from __future__ import division >>> a = 4 >>> b = 6 >>> c = a / b >>> c 0.66666666666666663
Method 2:
Similar to the C language:
c = a / float(b)
I believe that the examples described in this article will be helpful for everyone's Python program design.
The exact division command in python is incorrect.
From is followed by a space.
In python, what functions can be used to obtain the remainder of Division operations?
%.
3% 1 = 1