'using errors in conditions in python

I need help with my quadratic calculating program. I used an expression in an If, the expression will result in a math error obviously. But I don't want the code to break down when the error occurs instead, I want something else to happen.

import math


def quad(a, b, c):
    # creating a variable for all the parts that make the expression
    first_nu = int(a)
    second_nu = int(b)
    third_nu = int(c)
    four = 4
    two = 2
    det = second_nu ** 2 - (four * (first_nu * third_nu))

    if math.sqrt(det) == 0:
        print(' the discriminant is 0 hence the quadratic has no real roots')
    else:

        # calculating the roots
        root_det = math.sqrt(det)

        def printing():
            option1 = (-third_nu + root_det) / (two * first_nu)
            option2 = (-third_nu - root_det) / (two * first_nu)
            print(option1, option2)

        if det < 0:
            printing()
            print('The roots are not real roots')
        elif det == 0:
            print('mathematical error in a situation where there is root of 0')
            print('The roots has just one real root')
        elif det > 0:
            printing()
            print('The roots has two real roots')


first_num = input("enter your first number of the quadratic")
second_num = input("enter your second number of the quadratic")
third_num = input("enter your third number of the quadratic")

quad(first_num, second_num, third_num)


Solution 1:[1]

Use try: on the code you want to test and put the rest of the code in except. I hope this will solve the issue. For more information about Python error handling here or check from w3schools

The try block lets you test a block of code for errors.

The except block lets you handle the error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Philip Mutua