Search code examples
pythonpython-3.xreturn

return None in the end of the program in python


In the question they asked me to pick up numbers from the user and then solve a quadratic equation. I did it and check it on Python Tutor and every time it return me None, why is that?

def quadratic_equation(a,b,c):
import math
if a == 0:
    print("The parameter 'a' may not equal 0")
elif (b**2) - (4 * a * c) < 0:
    print("The equation has no solutions")
else:
### x1 mean with +
    x1 = ((-b) + (math.sqrt((b**2) - (4 * a * c)))) / (2 * a)
### x2 mean with - 
    x2 = ((-b) - (math.sqrt((b**2) - (4 * a * c)))) / (2 * a)
    if x1 and x2 is not None:
        return (f"The equation has 2 solutions: {x1} and {x2}")
    elif x1 is None:
        return (f"The equation has 1 solution: {x2} ")
    elif x2 is None:
        return (f"The equation has 1 solution: {x1} ")

def quadratic_equation_user_input():
numbers = (input("Insert coefficients a, b, and c: "))
num = []
for i in numbers.split():
    try:
        num.append(float(i))
    except ValueError:
        pass
a = num[0]
b = num[1]
c = num[2]
quadratic_equation(a,b,c)


print(quadratic_equation_user_input())

Solution

  • quadratic_equation_user_input calls quadratic_equation and ignores its return value, thus it returns None which is the default return value.

    # Call function but ignore return value
    quadratic_equation(a,b,c)
    
    # No return in caller function -> default to None
    # ....
    

    You probably meant

    return quadratic_equation(a,b,c)
    

    at the end of quadratic_equation_user_input.