How to verify if Valueerror occurred

Asked

Viewed 172 times

-1

I’m trying to make a program in Python that runs a second-degree equation: and delta is less than zero (no root exite); if it equals zero (only has a root); if it is greater than zero (there are two roots).

However my program does not work when delta is less than zero, I would like to take the type of error and run on "if" like this: if delta == ValueError:, I just couldn’t do it, there’s another alternative?

inserir a descrição da imagem aqui

  • 2

    Please click on [Edit] and put the code as text. Putting it as an image is not ideal, understand the reasons reading the FAQ.

  • I saw that you marked my answer as correct and then canceled. Was there anything missing, is there something you don’t understand? If that’s what it was, let me know that I can edit it by adding what’s missing, if that’s the case

  • No, thank you very much, I’m sorry I took so long to reply, but thank you very much, I didn’t know it was wrong because it was negative value (laughs).

  • Well, 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.

  • I’m sorry I took a print of the code, I’m new to Stack, next time I put as text.

2 answers

3


There’s nothing you can do if delta == ValueError because ValueError is an exception that is thrown by math.sqrt when you pass a negative value: exception is different from value returned, the ValueError (and any other exception) diverts the flow of the program; the exception nay is a value that is returned and assigned to variable delta. In that case you should use a block try/except to capture the exception. It would be something like this:

try:
    VALOR1 = (-BX + math.sqrt(DELTA)) / (2* AX2)
except ValueError: # se delta é negativo, math.sqrt lança um ValueError
    print('erro, não foi possível calcular a raiz de delta')

If delta is negative, math.sqrt spear one ValueError, and the code falls inside the block except.


But in fact none of this is necessary. Why don’t you test if the delta is negative before to calculate its square root? For if it is negative, there are no real roots and there is no point in trying to calculate them:

from math import sqrt

a = float(input("Digite o valor de A: "))
b = float(input("Digite o valor de B: "))
c = float(input("Digite o valor de c: "))

delta = b ** 2 - (4 * a * c)
if delta < 0:
    print("A raiz não existe")
elif delta == 0:
    print("a única raiz é : ", -b / (2 * a))
else: # se chegou aqui é porque delta é positivo
    raiz_delta = sqrt(delta) # aqui sim posso calcular a raiz quadrada sem problema
    print("o valor da primeira raiz é:  ", (-b + raiz_delta) / (2 * a))
    print("o valor da segunda raiz é:  ", (-b - raiz_delta) / (2 * a))

If the delta is negative, no need to calculate the square root, just print the message that there are no roots and that’s it. Note that here you do not need to make any calculations, since there are no roots, so there is nothing to calculate. So it doesn’t make sense to try to calculate the roots before knowing if the delta is negative. So you don’t do things for nothing and still prevent the ValueError occurs, not needing or dealing with the same.

If the delta is zero, you also do not need to calculate the square root, because it will be zero and will make no difference in the calculation: do -b + sqrt(delta) or -b - sqrt(delta), whereas the sqrt(0) is zero, is the same as simply using the value of -b, so I just did -b / (2 * a) (also note that you do not need to create two variables before, because in this case they will have same value).

Only if the delta is positive, then you calculate its square root. I didn’t create the variables VALOR1 and VALOR2 because you just want to print the result once and nothing else, but if you want to use your values to do other things later, then you can save them in variables.


If you want it to have complex roots (that is, it also works if the delta is negative), just change the module math for cmath:

from cmath import sqrt

a = float(input("Digite o valor de A: "))
b = float(input("Digite o valor de B: "))
c = float(input("Digite o valor de c: "))

delta = b ** 2 - (4 * a * c)
if delta == 0:
    print("a única raiz é : ", -b / (2 * a))
else:
    raiz_delta = sqrt(delta) # aqui sim posso calcular a raiz quadrada sem problema
    print("o valor da primeira raiz é:  ", (-b + raiz_delta) / (2 * a))
    print("o valor da segunda raiz é:  ", (-b - raiz_delta) / (2 * a))

In this case, I only dealt with the case of delta being zero, because there you do not need to calculate the root. For the other cases, the module cmath already treats correctly.


To another answer creates a function whose result is not used for anything (note that it calls the function, but the result is not stored anywhere), and then it still calculates the roots even if the delta is negative (that is, even when you don’t need it). It can even "work" (show the right messages for each case), but does unnecessary things and complicates for nothing something that is very simple to solve doing things in the right order, as indicated above.

  • 2

    What Mario always says: "Working is different from being right," you are right, it is not necessary to calculate the root when the deltar is negative and zero, I will not edit my answer to counter with yours and see that it is more correct than that. + 1

1

According to the Python 3.x documentation this error Valueerror is caused Generated when an operation or function receives an argument that has the right type but an inadequate value. ( Translated via google Translate).

In your specific case this error is why you are working the function math.sqrt with negative number, to get around this problem you need to define a function, as below:

import math
def raiz_quadrada(DELTA):
        return math.sqrt(-DELTA) 
AX2 = float(input("Digite o valor de A: "))
BX = float(input("Digite o valor de B: "))
C = float(input("Digite o valor de c: "))

DELTA = BX**2 - (4 * AX2 * C)
if DELTA < 0:
    raiz_quadrada(DELTA)


VALOR1 = (-BX + DELTA) / (2* AX2)
VALOR2 = (-BX - DELTA) / (2* AX2)

if DELTA == 0:
        print("a única raiz é : ", valor1)
else: 
    if DELTA < 0:
        print("A raiz não existe")
    else:
        print("o valor da primeira raiz é:  ", VALOR1)
        print("o valor da segunda raiz é:  ", VALOR2)

Looking for a more solution pythonica, you can use the library cmath, working with mathematical functions for complex numbers,that is to say, accepts negative numbers, with this only change math.sqrt for cmath.sqrt, so your code will be:

...
DELTA = BX**2 - 4 * AX2 * C
VALOR1 = (-BX + cmath.sqrt(DELTA)) / (2* AX2)
VALOR2 = (-BX - cmath.sqrt(DELTA)) / (2* AX2)
...

Browser other questions tagged

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