r/learnpython • u/shiny_arbok • Jul 13 '20
I wrote my first program today!
I'm a couple of days into learning Python and today I wrote my very first program for an idea I came up with myself, not because the book told me to!
It's a program to determine the value of the discriminant and x in an equation that follows "ax² + bx + c = 0", anyway here's the code:
# This is for calculating the discriminant when trying to find x in "ax² + bx + c = 0"
import math
try:
print("a?")
a = int(input())
print("b?")
b = int(input())
print("c?")
c = int(input())
def discr(a,b,c):
discriminant = b ** 2 - 4 * a * c
if discriminant < 0:
print("Discriminant =")
print(discriminant)
print("No value for x possible")
elif discriminant == 0:
print("Discriminant =")
print(discriminant)
print('x =')
print((-b)/(2*a))
elif discriminant > 0:
print("Discriminant =")
print(discriminant)
print('x = ')
print((-b + math.sqrt(discriminant))/(2*a))
print('x = ')
print((-b - math.sqrt(discriminant))/(2*a))
discr(a,b,c)
except ValueError:
print("That's not a number")
511
Upvotes
2
u/otanan Jul 13 '20
Yes for changing to floats!
As for the complex numbers, try looking into them, at a very basic level they serve as expanding on the real numbers (think, every normal number you work with, from -20, to 42.6423, to pi, to 10^100), where this expansion is done by allowing a definition of sqrt(-1).
In the case of solving the following quadratic: x^2+1=0, you've noticed that you'll get a negative discriminant and sure enough, if you just try
math.sqrt(-1)you'll get an error, but complex numbers allow us to make sense of these kinds of things! If you allow complex numbers you can use the quadratic formula to solve any quadratic, no need for the error handling for negative discriminants!Look into the
cmathpackage. If you change the import math line to:import cmaththen usecmath.sqrt(-1)You'll get something different! It's a complex number! I claim that this number actually is the square root of -1! How can you check that this is true?
It's a lot of fun to play around with these kinds of things, and the great thing about programming is that you can dive into all kinds of rabbit holes just as soon as you've found them! Explore!