0

I am just learning to code so i decided to make a project for myself making a function that finds the zero of a parabola. I think the issue i am having is actually printing out the sqrt.

This is the error I receive:

File "C:/Users/someb/AppData/Local/Programs/Python/Python37-32/Quadratic Formula Solver revised.py", line 10, in find_zero
    return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)
TypeError: unsupported operand type(s) for +: 'float' and 'str'

This is my like fifth revision of the code trying different ways, this originally was supposed to display the two different answers.

#Real Zero Finder QUadratic Formula
import math
def find_zero(a,b,c):
    discriminant = (b ** 2 - 4 * a * c)
    if discriminant < 0 :
        return "No real Zeros"
    elif discriminant == 0 :
        return "Vertex is the Zero"
    else:
        #This is where the error is taking place
        return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)

def disc(a,b,c):
    return math.sqrt(b ** 2 - 4 * a * c)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • The error is telling you that you can't add a number and a string together. When you call `float`, you're turning the argument into a number, and trying to add it to a string. You can't do that. – darthbith Oct 28 '18 at 19:37
  • https://docs.python.org/3.5/library/stdtypes.html#str.format – shadowtalker Oct 28 '18 at 20:01

3 Answers3

2

You're getting this error because Python doesn't know how to add a string to a float. You know you're trying to do concatenate the float to the string, but Python doesn't.

The simplest way to print multiple things in Python 3.6+ is to use formatted string literals (f-strings): https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings You put a f before your string and then put what you want to appear in the string inside curly braces { }.

return f'{-b} +- {math.sqrt(discriminant)} / {2 * a}'
pyj
  • 1,489
  • 11
  • 19
1

As mentioned above, you can't add strings and floats. Since you appear to be outputing a message, I'd prefer to fix this by converting the floats to strings, then the '+' will concatenate those strings. This returns a single string, which may be more useful that returning several values.

return str(-b) + " +- " + str(math.sqrt(discriminant)) + " / " + str(2 * a)

I also scrapped the float() conversions... I don't think they do anything here.

Paul Fornia
  • 452
  • 3
  • 9
-2

Problem is here in return:

return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)

you're trying to connect float to a String, instead of plus, use commas:

return float(-b), " +- ", float(math.sqrt(discriminant)), " / ", float(2 * a)