# Python2 and Python3 differences in division operations

Source: Internet
Author: User

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

Related Keywords:

### 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.