0

i typed a small function in python and the code is

def perimeter(side1,side2,side3):
    ''' (number,number,number)->float
    return the sum of side1,side2 and side3
    >>>perimeter(1,2,3)
     6.0
    >>>perimeter(4,5,7.1)
    16.1 '''

    result = side1+side2+side3
    return result 

but when i used it , the result was not on the shape of float , it was like the int . how can i make it in float sort ?

( i don't know how to form a the code window here so forgive me )

1
  • to get an accurate floating point sum: perimeter = lambda *sides: math.fsum(sides) Commented Apr 7, 2013 at 2:35

4 Answers 4

3

typecast to float

def perimeter(side1, side2, side3):
    return float(side1 + side2 + side3)
Sign up to request clarification or add additional context in comments.

Comments

2

Adding integers will produce an integer. You can convert one or all of them to float, or convert the result to float:

return float(result)

Comments

1

Maybe if his error is still happening after return float(side1 + side2 + side3), then he has to specify in the parameters that the sides are floats. def perimeter(float(side1),float(side2),float(side3)): Maybe that will work if nothing else is.

4 Comments

That's not syntactically valid.
It isn't? It just states the type that it is. Only if you pass a character it isn't valid.
Simply try it at the console. You can't do def f(float(x)): pass. Where did you see this used?
That's weird... maybe I am getting too used to Java and C++. My bad
1

If you want the same precision for every result try formatting

 return '%.3f' % result

1 Comment

This returns a string, not a number

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.