0

I am making a script where you can input a, b and c into the quadratic formula and it will give you the answer.

It says that b is not defined when I run it.

from cmath import sqrt
qf = lambda a, b, c: (-b-cmath.sqrt((b**2) - (4*a*c)))/(2*a), (-b+cmath.sqrt((b**2) - (4*a*c)))/(2*a)
a, b, c = input('Enter a, b and c with spaces in between the values \n').split()
a = float(a) ; b = float(b) ; c = float(c)
Print(qf(a, b,c)

Traceback (most recent call last): File "/storage/emulated/0/Download/.last_tmp.py", line 2, in qf = lambda a, b, c: (-b-cmath.sqrt((b2) - (4*a*c)))/(2*a), (-b+cmath.sqrt((b2) - (4*a*c)))/(2*a) NameError: name 'b' is not defined

2 Answers2

0

Check this out:

from math import sqrt

def get_roots(a, b, c):
    if a == 0:
        raise ZeroDivisionError('Not a quadratic equation')
    val = b ** 2  - 4 * a * c
    if val < 0:
        raise Exception('Imaginary Roots')
    val = sqrt(val)
    root1 = (-b - val) / (2 * a)
    root2 = (-b + val) / (2 * a)
    return root1, root2

a, b, c = input('Enter a, b and c with spaces in between the values \n').split()
a, b, c = float(a), float(b), float(c)
print(get_roots(a,b,c))
Prasad
  • 5,946
  • 3
  • 30
  • 36
0

Lambda functions can only return one thing so you need to group your outputs into either a tuple or a list by adding an enclosing () or []. The python parser is getting to:

qf = lambda a, b, c: (-b-sqrt((b**2) - (4*a*c)))/(2*a)

and assuming the lambda function is over. It then begins reading:

, (-b+sqrt((b**2) - (4*a*c)))/(2*a)

and tries to interpret -b in the global scope (where it doesn't exist) this gives you your name error. If you were to get rid of all the variables and for a moment pretend the second result of the quadratic formula was always 0, you'd get a tuple with the first element being a lambda function and the second being the integer 0

>>>qf = lambda a, b, c: [(-b-sqrt((b**2) - (4*a*c)))/(2*a),0
>>>qf
(<function <lambda> at 0x000002B44EF72F28>, 0)

This doesn't quite get what you're after, because you want a single function rather than a tuple of two separate functions to compute each root separately.

Here's what it'd look like if you want the lambda to return a list:

qf = lambda a, b, c: [(-b-sqrt((b**2) - (4*a*c)))/(2*a), (-b+sqrt((b**2) - (4*a*c)))/(2*a)]
Aaron
  • 10,133
  • 1
  • 24
  • 40