Considerations for using division in Python

Source: Internet
Author: User
The examples in this paper explain the considerations of the use of division in Python, which is a very important technique, and it is very useful for Python program design. The specific analysis is as follows:

Here's an example:

def avg (First, *rest):   return (first + sum (rest))/(1 + len (rest)) # Sample Use AVG (1, 2)    

The source program just to demonstrate the use of variable-length parameters, but in the Python 2.7.1 interpreter, I get the result is not the same as the result of the comment

>>> def avg (First, *rest): ...   return (first + sum (rest))/(1 + len (rest)) ...  

It can be clearly seen that the data after the decimal point is truncated, I remember dividing two integers, "//" should be the rounding, I remember wrong?

>>> def avg (First, *rest): ...   return (first + sum (rest))//(1 + len (rest)) # change "/' to '//' ...  

Change the "/" to "//", the result is the same, "//" is indeed to take the whole point I remember correctly, but why "/" The result is also truncated?

The same procedure I tested in 3.4.1 's interpreter and got the desired 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 '//' ...  

You can see that in 3.4.1 's interpreter, the "/" result retains the decimal place, and "//" is the result of rounding.

After searching, I found the question on StackOverflow: How does the Force division in Python result in a floating-point number? Note that this is for the 2.x version, 3.x there is no such problem
The first two solutions to the answer are good:

Method 1:

Method 2:

Similar to the practice in the C language:

c = a/float (b)

I believe that the examples described in this article will be helpful to everyone's Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.