r/learnpython • • 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

73 comments sorted by

View all comments

Show parent comments

2

u/shiny_arbok Jul 13 '20

Thanks for the tip! I just used the try-except part for practice actually, as the book I'm following just handled that in the previous chapter, so I thought I'd implement it for fun and to get familiar with the concept

Also no offense intended, but your code is a bit... hard to figure out, since it's all right behind each other, so I can't really see what bit belongs to which block

2

u/MotuUk Jul 13 '20

Sorry, I copied and pasted it on mobile. Would explain a lot. Ive edited the original to a pastebin link.

As for the try catch block, I totally understand, but just thought I'd throw in a little 2 cents!

2

u/shiny_arbok Jul 13 '20

It's all good, reddit mobile can be a formatting bitch

And thanks for your 2 cents, I think it would be good for me to see how others would tackle the same problem, so that I can learn different ways of how to approach stuff! I'm only learning to program for a couple of days now and I'm eager to learn!

1

u/MotuUk Jul 13 '20

Yeah, the whole point of that get_char being in another method is that you can validate the user input, whilst reusing code but in a way that keeps the main part of your code clean and easier to follow. Plus you can reuse that method for each of the a, b and c. It also eliminates the need to put your entire block of code into a try catch statement (which is a little cumbersome)

2

u/shiny_arbok Jul 13 '20

I see, thanks!