How to Divide Two Numbers in Python (Program + Algorithm)

To divide two numbers in Python, use the / operator: 17 / 5 gives 3.4. Use // for the whole-number part of the result, % for the remainder, and divmod() to get both at once. Below you’ll find a complete program that reads two numbers from the user, the algorithm and flowchart for it, and the details that trip people up: dividing by zero, negative numbers, and float precision.

Every example was run with Python 3.12.5; the output is copied from the terminal. For the full reference, see numeric types in the Python documentation.

Quick answer

a = 17
b = 5

print(a / b)     # division: always a float
print(a // b)    # floor division: whole-number quotient
print(a % b)     # remainder

Output:

3.4
3
2
Command Prompt screenshot of Python division, floor division and remainder: 17 / 5, 17 // 5 and 17 % 5
/, // and % run in the Command Prompt.

Python program to divide two numbers (with user input)

This program asks for the two numbers, keeps asking if the input isn’t a number, refuses a divisor of 0, and prints the result. float() accepts whole numbers and decimals:

# Python program to divide two numbers entered by the user

def read_number(prompt):
    while True:
        text = input(prompt)
        try:
            return float(text)
        except ValueError:
            print(f"  '{text}' is not a number, try again.")

dividend = read_number("Enter the dividend: ")
divisor = read_number("Enter the divisor: ")

while divisor == 0:
    print("  The divisor can't be 0.")
    divisor = read_number("Enter the divisor: ")

result = dividend / divisor
print(f"{dividend:g} / {divisor:g} = {result:.4g}")
Command Prompt screenshot of a Python program to divide two numbers: the user types 22, abc, 0 and 7 and gets 22 / 7 = 3.143
Real run: invalid input and a zero divisor are rejected before dividing.

Output of the run above (typed values: 22, abc, 0, 7):

Enter the dividend: 22
Enter the divisor: abc
  'abc' is not a number, try again.
Enter the divisor: 0
  The divisor can't be 0.
Enter the divisor: 7
22 / 7 = 3.143

And with 100 and 8:

Enter the dividend: 100
Enter the divisor: 8
100 / 8 = 12.5

Algorithm to divide two numbers

  1. Start.
  2. Read the dividend a.
  3. Read the divisor b.
  4. If b is 0, show a message and read b again.
  5. Calculate result = a / b.
  6. Print the result.
  7. Stop.
Flowchart of the algorithm to divide two numbers: start, read a, read b, check if b is zero and ask again, compute a divided by b, print the result, end
Flowchart of the division program.

Divide two variables

Division works the same with variables. Round the result for display with round() or an f-string:

price = 49.99
people = 3

share = price / people
print(share)
print(round(share, 2))
print(f"Each person pays {share:.2f}")

Output:

16.663333333333334
16.66
Each person pays 16.66

/, //, % and divmod(): which operator to use

a, b = 17, 5

print("a / b  =", a / b)
print("a // b =", a // b)
print("a % b  =", a % b)
print("divmod =", divmod(a, b))
print(10 / 2, type(10 / 2).__name__)       # / gives a float even when it divides evenly
print(10 // 2, type(10 // 2).__name__)

Output:

a / b  = 3.4
a // b = 3
a % b  = 2
divmod = (3, 2)
5.0 float
5 int
OperatorName17 and 5Result type
a / bDivision (true division)3.4Always float
a // bFloor division3int for ints, float if either is a float
a % bModulo (remainder)2Same as above
divmod(a, b)Quotient and remainder(3, 2)Tuple

For a deeper comparison of / and //, see normal division vs floor division in Python.

Watch out: // and % with negative numbers

// rounds down, not toward zero, so -17 // 5 is -4, not -3. The remainder then takes the sign of the divisor, so that (a // b) * b + a % b == a always holds:

import math

a, b = -17, 5

print("a // b        =", a // b)          # rounds DOWN (toward minus infinity)
print("a % b         =", a % b)           # takes the sign of the divisor
print("int(a / b)    =", int(a / b))      # truncates toward zero
print("math.fmod(a,b)=", math.fmod(a, b)) # remainder with the sign of the dividend
print("check:", (a // b) * b + a % b == a)

Output:

a // b        = -4
a % b         = 3
int(a / b)    = -3
math.fmod(a,b)= -2.0
check: True

Use int(a / b) or math.fmod() if you need the “truncate toward zero” behaviour of C, Java or JavaScript.

Division by zero

Dividing by zero raises ZeroDivisionError for both integers and floats. Catch it where a zero divisor is possible and return something sensible:

def safe_divide(a, b, default=None):
    try:
        return a / b
    except ZeroDivisionError:
        return default

print(safe_divide(10, 4))
print(safe_divide(10, 0))
print(safe_divide(10, 0, default=float("inf")))

for a, b in [(10, 0), (10.0, 0.0), (10, 0.0)]:
    try:
        a / b
    except ZeroDivisionError as err:
        print(f"{a!r} / {b!r}: ZeroDivisionError: {err}")

Output:

2.5
None
inf
10 / 0: ZeroDivisionError: division by zero
10.0 / 0.0: ZeroDivisionError: float division by zero
10 / 0.0: ZeroDivisionError: float division by zero
Command Prompt screenshot of a Python safe_divide function handling ZeroDivisionError
Handling division by zero with try/except.

Float precision: why 0.3 / 0.1 is not 3

Floats are stored in binary, and most decimal fractions can’t be stored exactly, so tiny errors appear. Round for display, or use Decimal (for money) or Fraction (for exact ratios) when the digits matter:

from decimal import Decimal
from fractions import Fraction

print(0.3 / 0.1)                            # floats are binary approximations
print(round(0.3 / 0.1, 10))                 # round for display
print(Decimal("0.3") / Decimal("0.1"))      # exact decimal arithmetic (pass strings!)
print(Fraction(1, 3) + Fraction(1, 6))      # exact fractions
print(Decimal(1) / Decimal(3))              # 28 significant digits by default

Output:

2.9999999999999996
3.0
3
1/2
0.3333333333333333333333333333

Create Decimal values from strings, not floats: Decimal(0.1) keeps the float’s tiny error.

Very large integers: / loses digits, // doesn’t

/ converts the result to a float, which has about 15 to 17 significant digits. Integer operators stay exact for any size:

big = 10**20 + 1

print(big / 1)          # converted to float: the last digit is lost
print(big // 1)         # integer arithmetic stays exact
print(int(big / 1) == big, big // 1 == big)

Output:

1e+20
100000000000000000001
False True

Format the result

a, b = 2, 3
result = a / b

print(result)
print(round(result, 2))          # a number, rounded
print(f"{result:.2f}")           # a string with 2 decimals
print(f"{result:.1%}")           # as a percentage
print(f"{7 / 3:.0f}")            # no decimals (rounded)

Output:

0.6666666666666666
0.67
0.67
66.7%
2

Divide two numbers without using the / operator

A common interview question. Repeated subtraction works but is slow for large numbers; subtracting doubled copies of the divisor (as below) needs far fewer steps:

def divide(dividend, divisor):
    """Integer division without / or //, by repeated subtraction of doubled divisors."""
    if divisor == 0:
        raise ZeroDivisionError("division by zero")
    negative = (dividend < 0) != (divisor < 0)
    dividend, divisor = abs(dividend), abs(divisor)
    quotient = 0
    while dividend >= divisor:
        chunk, multiple = divisor, 1
        while dividend >= chunk + chunk:      # double the chunk while it still fits
            chunk += chunk
            multiple += multiple
        dividend -= chunk
        quotient += multiple
    return -quotient if negative else quotient  # truncates toward zero, like int(a / b)

for a, b in [(17, 5), (100, 7), (-17, 5), (7, 10)]:
    print(f"{a:>4} / {b:<3} -> {divide(a, b):>3}   int(a / b) = {int(a / b)}")

Output:

  17 / 5   ->   3   int(a / b) = 3
 100 / 7   ->  14   int(a / b) = 14
 -17 / 5   ->  -3   int(a / b) = -3
   7 / 10  ->   0   int(a / b) = 0

Divide lists of numbers

values = [12, 7, 30, 45]
divisors = [3, 2, 5, 9]

print([v / d for v, d in zip(values, divisors)])
print([v / 3 for v in values])

Output:

[4.0, 3.5, 6.0, 5.0]
[4.0, 2.3333333333333335, 10.0, 15.0]

More in divide each element in a list by a number.

More beginner Python programs:

Frequently asked questions

How do you divide two numbers in Python?

Use the / operator, for example result = a / b. It always returns a float. Use // for a whole-number quotient and % for the remainder.

How do I write a Python program to divide two numbers entered by the user?

Read both with float(input(...)), check that the divisor isn’t 0, then print a / b. The full program above also re-asks when the input isn’t a number.

What is floor division in Python?

a // b divides and rounds the result down to the nearest whole number: 17 // 5 is 3 and -17 // 5 is -4.

Why does Python division return a float?

Since Python 3, / is “true division” and always returns a float, even for 10 / 2 (which gives 5.0). Use // if you want an integer.

How do I avoid ZeroDivisionError?

Check the divisor before dividing, or wrap the division in try / except ZeroDivisionError and return a default value.