bhylu.com

Advertisements

Arithmetic Operators

Arithmetic operators express sums, differences, products, division, powers, and remainders. Choose the division operation that matches the question.

Understand the idea

/ produces a true-division result. // floors the quotient, including for negative values, and % gives a remainder consistent with that floor division. ** raises a value to a power. Division by zero raises an exception, so validate or handle an invalid denominator when inputs come from outside the program.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

print(17 / 5)
print(17 // 5, 17 % 5)
print(-7 // 3)

Read the result

The results are 3.4, then 3 and 2, then -3. The last result floors toward negative infinity rather than truncating toward zero.

Try one change

Use divmod(17, 5) to obtain the quotient and remainder together and relate them to packing 17 items into boxes of five.