perform division using only subtraction in python

Here is a simple Python function that performs division using only subtraction:

main.py
def division(dividend, divisor):
    # Handle division by zero
    if divisor == 0:
        raise ZeroDivisionError('division by zero')

    quotient = 0
    sign = 1

    # Determine the sign of the quotient
    if dividend < 0:
        dividend = -dividend
        sign = -sign

    if divisor < 0:
        divisor = -divisor
        sign = -sign

    # Perform repeated subtraction
    while dividend >= divisor:
        dividend -= divisor
        quotient += 1

    # Apply the sign
    quotient *= sign

    return quotient
530 chars
27 lines

To use this function, simply call it with a dividend and a divisor:

main.py
>>> division(10, 2)
5
>>> division(5, 2)
2
>>> division(-5, 2)
-2
>>> division(10, 0)
ZeroDivisionError: division by zero
122 chars
9 lines

gistlibby LogSnag