简体   繁体   English

寻找一种更有效的方式来编写我的python程序

[英]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. 是的,您可以将disc移到一个仅计算值的函数中,然后将所有输入和输出逻辑作为单独的代码。 Some of your if statements are redundant too. 您的某些if语句也是多余的。 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!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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