[community edit: original title was “python conditionals”, OP is asking what is wrong with code below]
I made a function that’s supposed to determine if three sides can theoretically form a triangle. It works fine in my opinion , but when i input the code in pyschools.com website, it tells that in some test cases it doesn’t work (unfortunately it doesn’t show me the cases it didn’t work). Is something missing from my code, so in some special cases my logic breas down? Thank you very much for your help.
Here’s the function:
import math
def isTriangle(x, y, z):
if x > 0 and y > 0 and z > 0:
if x > y and x > z:
c = x
elif y > x and y > z:
c = y
else:
c = z
if c == math.sqrt(x**2 + y**2):
return True
else:
return False
else:
return False
It is easier to just do:
(edit: I have decided to say that
2,2,4is technically a triangle, but a degenerate triangle; change>=to>if you do not consider it to be a triangle.)This is exactly what you’re doing. You are calculating
c = largest = max(x,y,z)correctly, but then doingreturn math.sqrt(x**2+y**2)which checks if it is a right triangle.Demo:
Below I mention how your code can be simplified:
“if bool return True else return False” is the SAME as “return bool” in any almost any modern programming language. The former is unnecessarily verbose and should never be used.