Division and changing values

Lesson 21 of 54 · Python Foundations

Division answers different questions depending on the operator. / gives a floating-point quotient. // gives the floor of the quotient: the largest whole-number value no greater than it. % gives the corresponding remainder. For integer operands with a nonzero divisor, a == (a // b) * b + (a % b). Floating-point rounding can make that equality inexact when floats are involved.

print(17 / 5)
print(17 // 5)
print(17 % 5)
print(-17 // 5)
print(-17 % 5)
3.4
3
2
-4
3

For negative values, flooring moves toward negative infinity, not toward zero: -17 / 5 is -3.4, so the floor is -4. With integer inputs, // returns an integer; a float operand generally makes the result a float. All three division operators raise ZeroDivisionError for a zero divisor.

A variable can be updated using its existing value. Python evaluates the right side first, then binds the name to the result:

stock = 12
stock = stock - 3
stock += 2
stock *= 2
print(stock)
22

The values move from 12 to 9, then 11, then 22. +=, -=, *=, /=, //=, and %= are augmented assignment statements. For numbers, stock += 2 has the same result as stock = stock + 2. They are statements, so write the update separately from return. Other, mutable types can have different in-place behavior.

Chapter index