简体   繁体   中英

Looking for a more efficient way to write my python program

In my Trigonometry class, we were assigned to find the discriminant and conic section of an equation..

I wrote a function that calculates the discriminant, and then based on the value of the discriminant, prints the conic section...

I'm just curious if there is a better, more effective way to write this:

def disc():
    a_disc = raw_input("Please enter the value of A: ")
    b_disc = raw_input("Please enter the value of B: ")
    c_disc = raw_input("Please enter the value of C: ")
    disc = b_disc**2-4*(a_disc)*(c_disc)
    print ("The discriminant is: %s") % (disc)
    if disc < 0:
        if a_disc != c_disc:
            print ("The conic is an Ellipse!")
        elif a_disc == c_disc:
            print ("The conic is a Circle!")
    elif disc > 0:
        print ("The conic is a Hyperbola!")
    elif disc == 0:
        print ("The conic is a Parabola!")
    else:
        print ("Something went wrong...")
disc()

I don't fully understand using arguments inside of functions, but I feel like doing something like:

def disc(a,b,c):

would be the more clean approach I guess.


I would really appreciate any feedback anyone has to offer. Thanks in advance!

Yeah you could move disc into a function that just calculates the value, and then have all of the input and output logic as separate code. Some of your if statements are redundant too. Here's a slightly simpler version:

def disc(a, b, c):
    return b ** 2 - 4 * a * c


a = raw_input("Please enter the value of A: ")
b = raw_input("Please enter the value of B: ")
c = raw_input("Please enter the value of C: ")

val = disc(int(a), int(b), int(c))

print ("The discriminant is: %s") % (val)

if val == 0:
    print ("The conic is a Parabola!")
elif val > 0:
    print ("The conic is a Hyperbola!")
elif a != c:
    print ("The conic is an Ellipse!")
else:
    print ("The conic is a Circle!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM