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)
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}'