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
118
u/NFLAddict Jul 13 '20
cheers!
I like that your first program involved some math :)
But keep going!
one great way to learn, is to take it a step further; now that you completed a program, see if there's anything you can improve!
Just like with a paper, where someone might write a first draft, but afterwards, maybe they want to polish it up a bit. edits etc.
same can be done (and is often done), in programming. where you get your idea out; and then you can fix it up.
so, only take this as constructive and as a way to help you improve!
you can actually place the string you wanted to printout before input, inside the function
input(*inside*)so you can prompt for a,b,c like so:
Another thing, and I encourage you to learn more about them (google/youtube etc). is f-strings!
fstrings allow you to pass in a value between curly brackets {inside here}, and have it included in the string
perhaps more clear through example:
your lines:
can be written as:
unless you wanted them to printout on separate lines. in which case
"\n"is very useful as it signals a new line.so if you instead wrote:
that would behave, like you originally had it, but just all on one neat line. of course that's just one way: and I encourage you to play around with it a little bit, so I intentionally won't say anything about the other elif statements. but perhaps you can figure out a way to rewrite that with f-strings in a print()
but again: nice job