Skip to content

Module 4 · Operators — topic 5 of 16

Division

The / operator for true division: why it always returns a float, dividing by zero, rounding and formatting results, and choosing between /, // and Decimal.

Beginner 12 min read·Lesson 48 of 306 in Python Programming

Learning objectives

  • Explain why / always returns a float
  • Handle division by zero
  • Round and format division results

Definition

The / operator for true division: why it always returns a float, dividing by zero, rounding and formatting results, and choosing between /, // and Decimal.

Introduction

The / operator performs true division: it returns the exact mathematical result as a float, even when the numbers divide evenly. 10 / 2 is 5.0, not 5.

Why it matters

Averages, rates, percentages and unit prices all use division. Knowing that / always gives a float, and that dividing by zero stops the program, helps you produce correct, neatly formatted results without crashes.

Detailed explanation

In Python 3, / always returns a float. This avoids the old Python 2 surprise where 7 / 2 gave 3.

If the divisor is 0 (or 0.0), Python raises ZeroDivisionError. Check the divisor first or handle the exception.

Results may have many decimal places: 10 / 3 is 3.3333333333333335. Use round(value, 2) to store a rounded number or an f-string such as f"{value:.2f}" to display one.

Percentages: part / whole * 100 gives a percentage. Format with :.1f for one decimal place, or use the :% format, which multiplies by 100 for you.

When you need an integer result, use // instead. When you need exact decimal results, such as money, use integers or the Decimal type.

Division by a very small number produces a very large result, and dividing two large values can lose precision. In scientific work, check that values are in a sensible range before dividing, and remember that float("inf") can appear if a calculation overflows.

Syntax

Python
quotient = a / b
percentage = part / whole * 100
print(f"{quotient:.2f}")
  • / returns a float.
  • Check that b is not zero.
  • Format the result for display.

Code examples

Always a float

Python
print(10 / 2)
print(7 / 2)
print(10 / 3)
Output
5.0
3.5
3.3333333333333335

Formatting results

Python
share = 1000 / 3
print(round(share, 2))
print(f"{share:.2f}")
print(f"{45 / 60:.1%}")
Output
333.33
333.33
75.0%

More examples

Safe averages

Python
def average(values):
if len(values) == 0:
return None
return sum(values) / len(values)
for marks in ([72, 88, 95], []):
avg = average(marks)
if avg is None:
print("No marks yet")
else:
print(f"Average: {avg:.2f}")
try:
print(5 / 0)
except ZeroDivisionError as err:
print("ZeroDivisionError:", err)
Output
Average: 85.00
No marks yet
ZeroDivisionError: division by zero

Step-by-step explanation

  • average checks for an empty list before dividing, avoiding division by zero.
  • It returns None to mean “no average” rather than a misleading 0.
  • The loop prints a formatted average for the first list and a message for the empty one.
  • The last block shows the error Python raises if you divide by zero directly.

Expected output

Running “Safe averages” prints exactly:

TextOutput
Average: 85.00
No marks yet
ZeroDivisionError: division by zero

Practical applications

  • Dashboards divide counts to show conversion rates as percentages.
  • Fuel efficiency is distance divided by fuel used.
  • Unit prices compare products by dividing price by weight.
  • Exam portals divide marks obtained by maximum marks to report a percentage for each subject.

Best practices

  • Guard every division whose divisor could be zero.
  • Format results for display rather than printing raw floats.
  • Use // or Decimal when floats are the wrong tool.

Common mistakes

Dividing by a value that might be zero

Avoid

rate = done / total

Prefer

rate = done / total if total else 0

If total is 0 the program stops with ZeroDivisionError.

Comparing a division result exactly

Avoid

if 1 / 3 * 3 == 1:

Prefer

if math.isclose(1 / 3 * 3, 1):

Float division can introduce tiny rounding differences.

Key takeaways

  • / always returns a float.
  • Dividing by zero raises ZeroDivisionError.
  • Use round() or format specifiers for tidy results.

Try it yourself

  1. 1
    Ask for distance and time and print the average speed with two decimals, handling a time of zero.
  2. 2
    Print 37 out of 45 as a percentage with one decimal place.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is the type of 6 / 3 in Python 3?
Practise this topic