How to shorten my code

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

How to shorten my code

Post by m0nkeynutzs on Sat Mar 13, 2010 10:11 pm
([msg=36695]see How to shorten my code[/msg])

Ok guys,
Been lurking in the background quite a while, I mainly prefer reading others posts over asking questions which have been answered many times before.
However, I have only recently started learning about programming in Python, and need some tips on tidying up the code i have written. i.e. removing whitespace, minimizing unnecessary code etc.

The following is an area, perimeter and circumference calculator i wrote at work today, basically my first program in python (have done similar in VB and even [during my short attempt at learning the language] C++).
A lot of the blank lines used are for my own sake, they make it easier for me to read and debug, however even I can recognise that what i have written is very long and could be done using much less code, time and effort.

Would it be possible to get some feedback from some of the more experienced programmers on here on programming techniques i should learn, or just general tips, to write shorter and more efficient code?

Thanks in advance, :)

Code below:
Code: Select all
while True:
    option1 = input("\n\nWelcome to the Area and Perimeter Calculator, would you like to continue (y/n)?: ")

    if option1 == "y":

        option3 = input("Are you looking to find the Area and Perimeter / Circumference of a rectangle, circle or triangle? \n For a rectangle enter 'r', \n For a circle enter 'c', \n For a triangle enter 't', \n Please make your choice: ")

        if option3 == "r":

            l = float(input("\n Please input the length of the object: "))
            w = float(input("\n Please input the width of the object: "))
            area = float(l*w)
            perimeter = float((l*2)+(w*2))

            while True:
                option2 = input("\nWould you like to calculate Area 'a', Perimeter 'p', or Both 'b'?: ")

                if(option2 == "a"):

                    print("\n The area is ", area,", \n thank you for using.")
                    break

                elif(option2 == "p"):
               
                    print("\n The perimeter is ", perimeter,", \n thank you for using.")
                    break

                elif(option2 == "b"):

                    print("\n The area is: ", area, "\n The perimeter is: ", perimeter, "\n Thank you for using!.")
                    break

                else:
                    print("Please insert either a, p, or b to determine which answer you require.")

        elif option3 == "c":

            r = float(input("\n Please input the radius of the circle: "))
            area = float(3.141592 * (r**2))
            circ = float(2 * 3.141592 * r)
            while True:
                option2 = input("\nWould you like to calculate Area 'a', Circumference 'c', or Both 'b'?: ")

                if(option2 == "a"):

                    print("\n The area is ", area,", \n thank you for using.")
                    break

                elif(option2 == "c"):
               
                    print("\n The circumference is ", circ,", \n thank you for using.")
                    break

                elif(option2 == "b"):

                    print("\n The area is: ", area, "\n The perimeter is: ", circ, "\n Thank you for using!.")
                    break

                else:
                    print("Please insert either a, p, or b to determine which answer you require.")

        elif option3 == "t":

            print("\n This section is currently under construction!")

    elif option1 == "n":
        print("\n That's ok")
        break
    else:
        print("please answer either yes or no.")


print("\n All Calculations completed. \n Thank you for using!")
User avatar
m0nkeynutzs
New User
New User
 
Posts: 9
Joined: Sat Mar 06, 2010 9:05 pm
Location: Aus
Blog: View Blog (0)


Re: How to shorten my code

Post by insomaniacal on Sat Mar 13, 2010 11:05 pm
([msg=36698]see Re: How to shorten my code[/msg])

Personally, I think your code is a bit hard to read, but if spacing stuff out like that helps you, by all means, do so. Pretty much everything you wrote is necessary, but you could use functions in order to make the main program flow clearer. For example, defining a function for finding the area, then calling that function later on, whenever you needed to use it.

It's not really an issue with a small program like this, but it makes like a lot easier further down the line.
It's not who votes that counts, it's who counts the votes
insomaniacal.blog.com
User avatar
insomaniacal
Addict
Addict
 
Posts: 1210
Joined: Sun May 24, 2009 10:21 am
Blog: View Blog (0)


Re: How to shorten my code

Post by m0nkeynutzs on Sat Mar 13, 2010 11:16 pm
([msg=36699]see Re: How to shorten my code[/msg])

Yeh I understand it probably makes it harder for others to read, not sure why it makes it easier for me?.

With declaring functions, I was kind of thinking along those lines too, though i only ever needed to use a function (at most) twice so i didn't bother.
However, like you said, when developing larger programs it's basically a necessity.

Thank you for your (fast) reply :)

I'll just go back to lurking for now.. :mrgreen:
User avatar
m0nkeynutzs
New User
New User
 
Posts: 9
Joined: Sat Mar 06, 2010 9:05 pm
Location: Aus
Blog: View Blog (0)


Re: How to shorten my code

Post by DamegedSpy on Sun Mar 14, 2010 12:24 am
([msg=36706]see Re: How to shorten my code[/msg])

Good and extensive Commenting would help.
DamegedSpy
Poster
Poster
 
Posts: 273
Joined: Sat Dec 19, 2009 1:40 pm
Blog: View Blog (0)


Re: How to shorten my code

Post by m0nkeynutzs on Sun Mar 14, 2010 1:25 am
([msg=36707]see Re: How to shorten my code[/msg])

Ahhhhhhhh true.
I have a habit of not planning out projects nor using comments.

Thanks,
Any other feedback is appreciated guys.
User avatar
m0nkeynutzs
New User
New User
 
Posts: 9
Joined: Sat Mar 06, 2010 9:05 pm
Location: Aus
Blog: View Blog (0)


Re: How to shorten my code

Post by sanddbox on Sun Mar 14, 2010 1:33 am
([msg=36708]see Re: How to shorten my code[/msg])

m0nkeynutzs wrote:Ahhhhhhhh true.
I have a habit of not planning out projects nor using comments.

Thanks,
Any other feedback is appreciated guys.


By the way - only comment when it's useful.

For instance, you don't need to say:

private int sum = 0; //Here we initialize an integer called sum with a value of 0.

However, if a method is complex it's a good idea to comment. In addition, it's a good idea to comment the pre and post conditions of a method.
Image

HTS User Composition:
95% Male
4.98% Female
.01% Monica
.01% Goat
User avatar
sanddbox
Expert
Expert
 
Posts: 2331
Joined: Sat Jul 04, 2009 5:20 pm
Blog: View Blog (0)


Re: How to shorten my code

Post by m0nkeynutzs on Sun Mar 14, 2010 1:40 am
([msg=36709]see Re: How to shorten my code[/msg])

More for others sake, am i correct?
Say if you were planning to distribute your program as open source?

I have never needed to comment for my own sake, but at the same time i've never actually developed anything good outside of VB and Actionscript in Flash... I know it's a good habit to get into though, so i'll keep it in mind/.
Cheers all.
User avatar
m0nkeynutzs
New User
New User
 
Posts: 9
Joined: Sat Mar 06, 2010 9:05 pm
Location: Aus
Blog: View Blog (0)


Re: How to shorten my code

Post by eljonto on Sun Mar 14, 2010 4:18 am
([msg=36713]see Re: How to shorten my code[/msg])

Like you, I almost never plan stuff beforehand, and I very rarely comment my source. That being said, I lose interest with a lot of programming projects I do, then I regain interest later, come back and then have to spend a long time looking at my un-commented source to work out which approach i was taking to solve the problem. That is where comments are useful- also when you are learning to remind you of the function of some complicated things you might use but don't yet understand. Sanddbox made a valid point though- people say comment extensively but if you do what he did in his example you're gunna get pretty pissed off at programming :P
-Quis custodiet ipsos custodes?, Juvenal
_________________________________________________________________
User avatar
eljonto
Poster
Poster
 
Posts: 373
Joined: Thu Apr 17, 2008 1:16 am
Location: Australia
Blog: View Blog (0)


Re: How to shorten my code

Post by insomaniacal on Sun Mar 14, 2010 8:52 am
([msg=36723]see Re: How to shorten my code[/msg])

I'm not sure if this works for anyone else, but I generally like to code in blocks, and comment right before the block starts. Each block has one purpose. So a menu made out of if, elif,else statements would all be single spaced, and then one or two extra spaces would be added before the next "block".

I'm not sure if that'll work for you, but just thought I'd through my two-cents in.
It's not who votes that counts, it's who counts the votes
insomaniacal.blog.com
User avatar
insomaniacal
Addict
Addict
 
Posts: 1210
Joined: Sun May 24, 2009 10:21 am
Blog: View Blog (0)


Re: How to shorten my code

Post by the0nlyb0ss on Sun Sep 19, 2010 10:15 pm
([msg=46151]see Re: How to shorten my code[/msg])

This isn't exactly for shortening but more so for efficiency sake, when the user enters a letter in any of your input() prompts, you should convert their answer to uppercase, that way it won't spit out an error if you put an 'A' instead of 'a'.
I just got into the habit of doing this in my code to make it a bit less error prone.

For example:
Code: Select all
choice = input("Please enter the word 'foobar': ")
#If they enter fOObAr, it'll still be okay:
choice = choice.upper()      #This is the uppercase conversion
if choice != "FOOBAR":
    print("Expected 'foobar' got {0}.".format(choice.upper()))
else:
    print("Thank you!")
"Knowledge is knowing that a tomato is a fruit, but Wisdom is knowing not to put it in a fruit salad."
User avatar
the0nlyb0ss
Experienced User
Experienced User
 
Posts: 54
Joined: Thu Sep 02, 2010 11:24 pm
Location: California
Blog: View Blog (0)


Next

Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests