How to calculate division using subtraction operation only?

Asked

Viewed 284 times

2

I’m trying to put a command line that does division from subtraction into a dictionary but would be causing error, would know where I’m going wrong?

x = float(x)
y = float(y)
num = 0
if y != 0:
    if (x>0) and (y>0):
        def Divisão (x, y):
            while (x >= y):
                x = x - y
                num = num + 1
            return num
        print(f"Seu resultado é: {Divisão(x, y)}")
    elif (x>0) and (y<0):
        y = -(y)
        def Divisão(x, y):

            while (x>0):
                x = x - y
                num = num - 1
            return num
        print(f"Seu resultado é: {Divisão(x, y)}")        
    elif (x<0) and (y>0):
        x = -(x)
        def Divisão(x, y):
            while (x>0):
                x = x - y
                num = num - 1
            return num                
        print(f"Seu resultado é: {Divisão(x, y)}")
    else:
        x= -(x)
        y= -(y)
        def Divisão (x, y):

            while (x>0):
                x = x - y
                num = num + 1
            return num
        print(f"Seu resultado é: {Divisão(x, y)}")

2 answers

6

The reserved word def serves to create a function. In your code you are creating a different version of the function for each condition of your if, but you don’t need this.

A simpler way is to place these conditions within the function, and define it only once. Example:

def dividir(x, y):
    if y == 0:
        raise ZeroDivisionError('Não pode dividir por zero')

    sinal = 1
    # ajusta os valores e o sinal do resultado
    if x < 0:
        x = -x
        sinal *= -1
    if y < 0:
        y = -y
        sinal *= -1

    result = 0
    while x >= y:
        x -= y
        result += 1
    return result * sinal

First I do a check to avoid division by zero. Then I do the checks on the x and y signal. Note that if x is negative I turn the signal from 1 to -1, so I can adjust the final result. The same thing is made for y.

Finally, I loop the subtractions, and the final result is adjusted according to the signal.

This way the function already treats all cases and you do not need to define it four times.

Also note the syntax x -= y, which is equivalent to x = x - y (as well as sinal *= -1 is the same as sinal = sinal * -1, and result += 1 is the same as result = result + 1 - attention: not always these two forms are equivalent, but for this particular case, the result is the same).


Running your code, I got this error:

UnboundLocalError: local variable 'num' referenced before assignment

This is because num was declared outside the function Divisão, but you are using it within the function. A solution would be to initialize it within the function:

def Divisão (x, y):
    num = 0 # <--- aqui
    while (x >= y):
        x = x - y
        num = num + 1
    return num

So you create a local variable num (that is not the same num that was created outside the function).

Or you can indicate that you want to use the num global (which is outside the function):

def Divisão (x, y):
    global num
    while (x >= y):
        x = x - y
        num = num + 1
    return num

But in this case, I still think the best solution is to define the function only once, as I already suggested above.

  • Yes, I also applied this method and I function, another one that I tested and I function was also put my variable in one, in the def and in the print. Thank you very much !!

  • @Xiruxin If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

2

You didn’t post the error that gives you, however looking at your code I think I shouldn’t be putting so many functions Divisão(), remove this. I’ll give you the first block of if to see how it looks:

if (x>0) and (y>0):
        while (x >= y):
            x = x - y
            num = num + 1
    print(f"Seu resultado é: {num}")

Moral of the story: you should only create the function Divisão() if it could be used by the other blocks of if/else, as in your case each block needs a different function simply Replace the result without resorting to functions. I think that would be causing you problems because you are referring to the variable num before declaring or passing it as a parameter to the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.