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/hipstergrandpa Jul 14 '20
Nice! One thing I’m not sure is covered by other comments is the use of the ‘try/except’ being used here. Generally, you want to use try and except to catch and gracefully handle known sources of that exception, rather than blanketing the entire function. The idea is to isolate problems for debugging so you know exactly where some issue may occur. In this case, you want to catch a value error from user input. The best place to put the try and except then would be around just the inputs, as you’ll get a value error when you try to cast the input into an int. If you get an unrelated error that happens to be a value error as well, you’d have a harder time determining where it came from as your program will just tell you it isn’t a number, when that may not be the source of error at all. Something I learned that I thought you would find helpful :)