How do you divide 2 in python?

How can I divide two numbers in Python 2.7 and get the result with decimals?

I don't get it why there is difference:

in Python 3:

>>> 20/15
1.3333333333333333

in Python 2:

>>> 20/15
1

Isn't this a modulo actually?

Håken Lid

21.5k9 gold badges47 silver badges64 bronze badges

asked Jan 23, 2014 at 18:54

4

In Python 2.7, the / operator is integer division if inputs are integers.

If you want float division [which is something I always prefer], just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %:

>>> 7 % 2
1
>>> 7 // 2
3
>>>

As commented by user2357112, this import has to be done before any other normal import.

answered Jan 23, 2014 at 19:01

bgusachbgusach

13.8k11 gold badges49 silver badges63 bronze badges

8

In Python 3, / is float division

In Python 2, / is integer division [assuming int inputs]

In both 2 and 3, // is integer division

[To get float division in Python 2 requires either of the operands be a float, either as 20. or float[20]]

answered Jan 23, 2014 at 18:56

mhlestermhlester

22.2k10 gold badges50 silver badges74 bronze badges

1

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float[15]

answered Jan 23, 2014 at 19:00

woozykingwoozyking

4,6521 gold badge22 silver badges29 bronze badges

"/" is integer division in Python 2, so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float[20]/15 #1.33333333

answered Jan 23, 2014 at 19:02

BryanBryan

1,74812 silver badges12 bronze badges

Basics[edit | edit source]

Python math works as expected:

>>> x = 2
>>> y = 3
>>> z = 5
>>> x * y
6
>>> x + y
5
>>> y - x
1
>>> x * y + z
11
>>> [x + y] * z
25
>>> 3.0 / 2.0 # True division
1.5
>>> 3 // 2 # Floor division
1
>>> 2 ** 3 # Exponentiation
8

Note that Python adheres to the PEMDAS order of operations.

Powers[edit | edit source]

There is a built in exponentiation operator **, which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations.

Floor Division and True Division[edit | edit source]

In Python 3.x, slash operator ["/"] does true division for all types including integers, and therefore, e.g. 3/2==1.5[1][2]. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.

In Python 3.x and latest 2.x, floor division for both integer arguments and floating-point arguments is achieved by using the double slash ["//"] operator. For negative results, this is unlike the integer division in the C language since -3 // 2 == -2 in Python while -3 / 2 == -1 in C: C rounds the negative result toward zero while Python toward negative infinity.

Beware that due to the limitations of floating point arithmetic, rounding errors can cause unexpected results. For example:

>>> print[0.6/0.2]
3.0
>>> print[0.6//0.2]
2.0

For Python 2.x, dividing two integers or longs using the slash operator ["/"] uses floor division [applying the floor function after division] and results in an integer or long. Thus, 5 / 2 == 2 and -3 / 2 == -2. Using "/" to do division this way is deprecated; if you want floor division, use "//" [available in Python 2.2 and later]. Dividing by or into a floating point number will cause Python to use true division. Thus, to ensure true division in Python 2.x: x=3; y=2; float[x]/y == 1.5.

Links:

  • 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org
  • Python-style integer division & modulus in C, stackoverflow.com
  • Integer division rounding with negatives in C++, stackoverflow.com
  • In Python, what is a good way to round towards zero in integer division?, stackoverflow.com
  • Why Python's Integer Division Floors, python-history.blogspot.com

Modulus[edit | edit source]

The modulus [remainder of the division of the two operands, rather than the quotient] can be found using the % operator, or by the divmod builtin function. The divmod function returns a tuple containing the quotient and remainder.

>>> 10 % 7
3
>>> -10 % 7
4

Note that -10 % 7 is equal to 4 while it is equal to -3 in the C language. Python calculates the remainder as one after floor division while the C language calculates the remainder after C integer division, which differs from Python's floor division on integers: C integer division rounds negative results toward zero.

Links:

  • 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org

Negation[edit | edit source]

Unlike some other languages, variables can be negated directly:

Comparison[edit | edit source]

OperationMeans
< Less than
> Greater than
= Greater than or equal to
== Equal to
!= Not equal to

Numbers, strings and other types can be compared for equality/inequality and ordering:

>>> 2 == 3
False
>>> 3 == 3
True
>>> 3 == '3'
False
>>> 2 >> "a" >> [1,2,3] == [1,2,3]
True
>>> [1,2,3] is [1,2,3]
False

For the built-in immutable data types [like int, str and tuple] Python uses caching mechanisms to improve performance, i.e., the interpreter may decide to reuse an existing immutable object instead of generating a new one with the same value. The details of object caching are subject to changes between different Python versions and are not guaranteed to be system-independent, so identity checks on immutable objects like 'hello' is 'hello', [1,2,3] is [1,2,3], 4 is 2**2 may give different results on different machines.

In some Python implementations, the following results are applicable:

print[8 is 8]           # True
print["str" is "str"]   # True
print[[1, 2] is [1, 2]] # False - whyever, it is immutable
print[[1, 2] is [1, 2]] # False
print[id[8] == id[8]]   # True
int1 = 8
print[int1 is 8]        # True
oldid = id[int1]
int1 += 2
print[id[int1] == oldid]# False

Links:

  • 3. Data model, python.org
  • 2. Built-in Functions # id, python.org
  • 5. Expressions # is, python.org

Augmented Assignment[edit | edit source]

There is shorthand for assigning the output of an operation to one of the inputs:

>>> x = 2
>>> x # 2
2
>>> x *= 3
>>> x # 2 * 3
6
>>> x += 4
>>> x # 2 * 3 + 4
10
>>> x /= 5
>>> x # [2 * 3 + 4] / 5
2
>>> x **= 2
>>> x # [[2 * 3 + 4] / 5] ** 2
4
>>> x %= 3
>>> x # [[2 * 3 + 4] / 5] ** 2 % 3
1

>>> x = 'repeat this  '
>>> x  # repeat this
repeat this
>>> x *= 3  # fill with x repeated three times
>>> x
repeat this  repeat this  repeat this

Logical Operators[edit | edit source]

Logical operators are operators that act on booleans.

or[edit | edit source]

The or operator returns true if any one of the booleans involved are true. If none of them are true [in other words, they are all false], the or operator returns false.

if a or b:
    do_this
else:
    do_this

and[edit | edit source]

The and operator only returns true if all of the booleans are true. If any one of them is false, the and operator returns false.

if a and b:
    do_this
else:
    do_this

not[edit | edit source]

The not operator only acts on one boolean and simply returns its opposite. So, true turns into false and false into true.

if not a:
    do_this
else:
    do_this

The order of operations here is: not first, and second, or third. In particular, "True or True and False or False" becomes "True or False or False" which is True.

Warning, logical operators can act on things other than booleans. For instance "1 and 6" will return 6. Specifically, "and" returns either the first value considered to be false, or the last value if all are considered true. "or" returns the first true value, or the last value if all are considered false.

Bitwise Operators[edit | edit source]

Python operators for bitwise arithmetic are like those in the C language. They include & [bitwise and], | [bitwise or], ^ [exclusive or AKA xor], > [shift right], and ~ [complement]. Augmented assignment operators [AKA compound assignment operators] for the bitwise operations include &=, |=, ^=, =. Bitwise operators apply to integers, even negative ones and very large ones; for the shift operators, the second operand must be non-negative. In the Python internal help, this is covered under the topics of EXPRESSIONS and BITWISE.

Examples:

  • 0b1101 & 0b111 == 0b101
    • Note: 0b starts a binary literal, just like 0x starts a hexadecimal literal.
  • 0b1 | 0b100 == 0b101
  • 0b111 ^ 0b101 == 0b10
  • 1 > 1 == 3
  • 1

Chủ Đề