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/MotuUk Jul 13 '20 edited Jul 13 '20
Well done mate! Looks good.
Couple of pointers that it doesn't look like anyone else has picked up on. For one, I would put your method discr() outside of the try block. It will only be defined by the python compiler once it has passed all of the input calls, or never if you get an error (could lead to issues in a longer piece of code).
Another thing, there isn't much point in the try catch block in the first place as if the error is handled or not it still ends the program, but I guess it let's you know! Instead, what I've done in the past (example is from an old hangman game of mine) is something along the lines of:
def get_char():
char = get_char()
But change this for getting an int.
Edit: pastebin link due to horrible formatting...