[Tutor] Code Problem

Alan Gauld alan.gauld at btinternet.com
Thu Mar 10 20:57:07 EST 2016


On 10/03/16 20:30, Ben Conklin wrote:

> show if it is a equilateral, isosceles, or right triangle. I have it so
> that it makes s1 the longest side, and s2 and s3 the other 2 sides. The
> right triangle equation should be right, but is not outputting anything.

The easiest way to find that is just use the max() function

longest = max(s1,s2,s3)

> def main():
>     s1, s2, s3 = eval(input("Enter the three side lengths of a triangle: "))

Using eval() is a security hazard and you should avoid it.
You can convert your input to three strings using the
split() function, then convert them to int/float.

>     if s2 > s1:
>         temp = s1
>         s1 = s2
>         s2 = temp

In Python you can shortcut all of that reversing code with

s1,s2 = s2,s1


>     if s3 > s1:
>         temp = s1
>         s1 = s3
>         s3 = temp

and

s1,s3 = s3,s1

You wind up with

>     if s2 + s3 > s1:
>         print("This is a triangle")
>         if s1 == s2 and s2 == s3 and s3 == s1:
>             print("This is an equilateral triangle")
>         elif s1 == s2 or s2 == s3 or s3 == s1:
>             print("This is an isosceles triangle")
>         if s1**2 == s2**2 + s3**2: #This will not output a square triangle
> when entered
>             print("This is a right triangle")

It should work for integer values but possibly not if
you entered floats. That's because floating point numbers
are not represented exactly in the computer and so testing
two floating point numbers for equality often does not work.

Other than that it looks to me like it should work.

You might also like to add a debugging step to print s1,s2
and s3 just before your if statements, just to check they
are the values you expect.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list