Hi,

I'm newbie in Python Programming. I created the below code. I want to optimize it, but dont know where to start. I am sure, I can do the same with less lines of code. Please advise on best practices and ways on how to optimize it.

import math

def side_1():

    print ''
    print "**********************************"
    print "     Pythagorean Calculator        "
    print "**********************************"
    print ''
    a = raw_input("Please enter the value of A: ")
    b = raw_input("Please enter the value of B: ")
    if a.isalpha():
        print "Sorry, that is not a valid option."
    else:
        a = float(a)
        b = float(b)
        c = math.sqrt((a**2) + (b**2))
        print "The value for A: " + "%.2f" % round(a,2)
        print "The value for B: " + "%.2f" % round(b,2)
        print "The value for C: " + "%.2f" % round(c,3)
        print ''

    flag = raw_input('Would you like to run the program again? [Y/N] ').upper()
    if flag == 'Y' and flag.isalpha():
        print ''
        print("Let's proceed")
        side_1()
    else:
        print('I will quit')
        print('')

def side_2():
    print ''
    print "**********************************"
    print "     Pythagorean Calculator        "
    print "**********************************"
    print ''
    b = raw_input("Please enter the value of B: ")
    c = raw_input("Please enter the value of C: ")
    if b.isalpha():
        print "Sorry, that is not a valid option."
    else:
        b = float(b)
        c = float(c)
        a = math.sqrt((b**2) - (c**2))
        print "The value for B: " + "%.2f" % round(b,2)
        print "The value for C: " + "%.2f" % round(c,2)
        print "The value for A: " + "%.2f" % round(a,3)
        print ''

    flag = raw_input('Would you like to run the program again? [Y/N] ').upper()
    if flag == 'Y' and flag.isalpha():
        print ''
        print("Let's proceed")
        side_2()
    else:
        print('I will quit')
        print('')


def side_3():
    print ''
    print "**********************************"
    print "     Pythagorean Calculator       "
    print "**********************************"
    print ''
    c = raw_input("Please enter the value of C: ")
    a = raw_input("Please enter the value of A: ")
    if c.isalpha():
        print "Sorry, that is not a valid option."
    else:
        c = float(c)
        a = float(a)
        b = math.sqrt((c**2)- (a**2))
        print "The value for A: " + "%.2f" % round(a,2)
        print "The value for C: " + "%.2f" % round(c,2)
        print "The value for B: " + "%.2f" % round(b,3)
        print ''

    flag = raw_input('Would you like to run the program again? [Y/N] ').upper()
    if flag == 'Y' and flag.isalpha():
        print ''
        print("Let's proceed")
        side_3()
    else:
        print('I will quit')
        print('')


def main():
    print ''
    print "**********************************"
    print "     Pythagorean Main Menu       "
    print "**********************************"
    print" 1. I have side A and B"
    print" 2. I have side B and C"
    print" 3. I have side C and A"
    option = raw_input('Please select an option:')
    if option == '1':
        side_1()
    elif option == '2':
        side_2()
    elif option == '3':
        side_3()
    else:
        print "Not a Valid option"
        main()

main()

Optimizing is different from reducing code size. Optimizing usually means change the code in order to reduce the execution time. Changing the code in order to have a better looking and shorter code is part of refactoring.

The first criterion is code repetition. The functions side_1(), side_2(), side_3() are almost identical, they can be merged into a single function

def side(first, second):
    ...

then

    if option == '1':
        side('A', 'B')
    elif option == '2':
        side('B', 'C')
    elif option == '3':
        side('C', 'A')
    else:
        print "Not a Valid option"
        main()

I would further recommend re-writing the side() function by removing the user interaction, so that the function is responsible solely for computing the desired result:

def pythagorean(first, second):
    ''' pythagorean(float, float) - 
    Function to compute the length of a side of a triangle
    from the lengths of the other two sides.'''
    return math.sqrt((first**2) - (second**2))

# ... later ...

result = pythagorean(3, 4)  # result will equal 5 

The reason for this threefold. First, it simplifies the function, so that it is clearer what it is meant to do. Second, it generalizes the function, making it easier to use in different places for different purposes. Third, it is generally a good idea to separate the code that performs the actual computation from the user interaction, so that it is easier to change either or both of them without interfering with the other; mixing two different operations generally makes for code that is difficult to maintain. Separating the code this way is just a good way of avoiding future issues.

Note also that I added a simple docstring comment to the function. This makes it so that pydoc (the Python documentation tool) can extract the docstring and generate user documentation for the function automatically.

Thanks!! Exactly what I was looking for .. I will modify the code with your suggestions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.