4
\$\begingroup\$

This is the first mini-project I have completed by myself with Python 2.7. I wrote a simple program that calculates the area of different two-dimensional shapes and it works. I want to know what you think of it and also want to know how it can be improved and if I did something wrong, so this is my code:

def circle(pi,radius):
    area_circle = pi * (radius ** 2)
    print " the area of your circle equals %s" % (area_circle)
def rectangle(length, width):
    area = length * width
    print "The area of your rectangle equals %s" %(area)
def triangle(height, base):
    area_triangle = height * base * 0.5
    print "the area of your triangle equals %s" % (area_triangle)
def square(length):
    area_square = length ** 2
    print "the area of your square equals %s" % (area_square)
shapes = ["square", "rectangle", "triangle", "circle"]
print "Area calculator!"
print "Made by Ahmed Fawzy"
print "-------------------------------"
def calculation():
    print "please type the name of your shape"
    print "(Square, Rectangle, Triangle, Circle)"
    user_shape = raw_input()
    if user_shape == shapes[0]:
        square(length = float(raw_input("please type the length of the square.")))
    elif user_shape == shapes[1]:
        rectangle(length = float(raw_input("please type the length of the rectangle.")), width = float(raw_input("please type the width of the rectangle.")))
    elif user_shape == shapes[2]:
        triangle(height = float(raw_input("please type the height of the triangle.")), base = float(raw_input("please type the base length of the triangle.")))
    elif user_shape == shapes[3]:
        circle(3.14, radius = float(raw_input("please type the radius of the circle.")))
    else:
        print "That's not in the choices!, Try again."
        calculation()
calculation()
choice = raw_input("Would you like to calculate the area of a different shape?(yes/no)")
while choice == "yes":
    print "---------------------"
    calculation()
    choice = raw_input("Wanna go again?")

There's one more thing I'd like to add but don't know how, I want to make it infinite loop when the user types an answer different than 'yes' or 'no' to the "would you like to calculate the area of a different shape?" , until the user types the correct answer which is yes or no then the loop breaks and it calculates again, any tips?

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review. We will review your code, but we cannot tell you how to add the new feature. Hint: try a while True loop and the break keyword. \$\endgroup\$
    – user34073
    Commented Mar 28, 2016 at 15:23

2 Answers 2

1
\$\begingroup\$

Nice job! When I was learning how to program Python, I also wrote a program to work with geometries.

Spaces

Its always a good idea to space things out a little more. PEP 8 recommends 2 newlines between each function definition, just so it doesn't look as intimidating.

Function return values

I noticed that you print the values instead of returning them. This is fine, but it makes more sense encapsulation wise if you return them. The resulting code would look something like this:

def circle(pi,radius):
    area_circle = pi * (radius ** 2)
    return area_circle

Then, later on...

print(" the area of your circle equals %s" % (circle(pi, radius)))

Formating values

Instead of formatting strings this way:

" the area of your circle equals %s" % (some_value)

Try this way:

" the area of your circle equals {}".format(some_value)

It is becoming the standard for string formatting, and the developers even wanted to stop using the traditional % notation. Here is the documentation page on how the .format() method works

Recursion???

Your function calculate calls itself, and this should only be used in cases where it is absolutely necessary. Here it is not. You can knock out this error, and solve the user input error problem in one shot. To do this, I'd merge the input taking from calculation, and the main loop. Its always nice to take input from the user in only one place:

def calculation(user_shape):
    if user_shape == shapes[0]:
        length = float(raw_input("please type the length of the square."))
        return square(length)
    elif user_shape == shapes[1]:
        length = float(raw_input("please type the length of the rectangle."))
        width = float(raw_input("please type the width of the rectangle."))
        return rectangle(length, width)
    elif user_shape == shapes[2]:
        height = float(raw_input("please type the height of the triangle."))
        base = float(raw_input("please type the base length of the triangle."))
        return triangle(height, base)
    elif user_shape == shapes[3]:
        radius = float(raw_input("please type the radius of the circle."))
        return circle(3.14, radius)

choice = 'y'
while True:
    if choice not in ('y', 'n'):
        choice = raw_input("Would you like to calculate the area of a different shape? Your has to be a 'y' or a 'n'(y/n)")
        continue
    print "---------------------"

    print "please type the name of your shape"
    print "(Square, Rectangle, Triangle, Circle)"
    response = raw_input()
    if response not in shapes:
        print "That's not in the choices!, Try again."
        choice = 'y'
        continue

    print(calculation(response))
    choice = raw_input("Would you like to calculate the area of a different shape?(y/n)")

Pi, and other constants in general

Also, in the math library, there exists pi constant, that is more accurate then the value you used here (3.14). To access it, just type from math import pi at the very top of your file. You can probably then take that value and hard code it into the function itself, as passing it in doesn't make any sense.

\$\endgroup\$
2
  • \$\begingroup\$ That is absolutely helpful and you're right about the function calling itself and i especially liked how you made an infinite loop until the user answers correctly using while True: , but there are a few things that i don't quite get and i need further explanation if you don't mind, first of all : why did you declare choice = 'y' before the loop , why is it necessary? and second : what does the "continue" function do or mean after the loop? and last of all : what does the (response) parameter in calculate refer to? Thanks ! \$\endgroup\$ Commented Mar 28, 2016 at 18:59
  • \$\begingroup\$ Okey Dokey. I set choice equal to 'y' before anything even began so that the peogram would not run into a NameError in the line if choice not in .... It basically answers for the user 'yes' the first time it runs, otherwise why would they even start up the module? Secondly, the continue keyword almost acts lie a break, but instead of exiting the function, it will jump back up to the top and run the next iteration. What is the response? Good question, I have no idea, definitely a typo, ill fix it now. \$\endgroup\$ Commented Mar 28, 2016 at 19:19
1
\$\begingroup\$

Generally looks good so far (I especially like how you set length and width to an inline call to raw_input() -- less code's better).

One suggestion is to only take radius as a parameter to the circle function and instead use the math.pi constant and import math at the top of the program, making the top of your program the following:

import math
def circle(radius):
   area_circle = math.pi * (radius ** 2)
   print " the area of your circle equals %s" % (area_circle)

To add the thing where you keep prompting the user for yes or no until they enter on of them, although I suppose I can't give you code (think that's what StackOverflow is for), think about initializing the response string to something that isn't "yes" or "no" outside a while loop where you keep checking if it's a valid response and asking the user for input...

\$\endgroup\$
1
  • \$\begingroup\$ Thanks a lot ! can't believe i haven't thought about importing math before, and thanks for the suggestion . \$\endgroup\$ Commented Mar 28, 2016 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.