如何调试我的 Python 代码以检查数据是否可以形成三角形
How can I debug my Python code to check if data can form a triangle or not
代码的目的是找出是否可以用给定的参数形成三角形。理论告诉我们 任意两个边的总和应该大于第三个边 并且根据我正在编码但它没有显示正确答案。
我的任务是 return True 如果参数允许,return False不是。
def isItATriangle(a, b, c):
if a + b > c or a + c > b or b + c > a:
return True
else:
return False
print(isItATriangle(1 , 1, 3))
为什么代码不能正常运行?
而不是
if a + b > c or a + c > b or b + c > a:
return True
else:
return False
右边主要代码展示了这个
if a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True
我如何确定我在逻辑的哪一部分是错误的?
为了 return 为真,您必须满足 所有 条件,而不仅仅是其中一个。因此,您的代码应该是:
def isItATriangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
return True
else:
return False
print(isItATriangle(1 , 1, 3))
更正和简化:
def isItATriangle(a, b, c):
return a + b > c and a + c > b and b + c > a:
print(isItATriangle(1 , 1, 3))
代码的目的是找出是否可以用给定的参数形成三角形。理论告诉我们 任意两个边的总和应该大于第三个边 并且根据我正在编码但它没有显示正确答案。
我的任务是 return True 如果参数允许,return False不是。
def isItATriangle(a, b, c):
if a + b > c or a + c > b or b + c > a:
return True
else:
return False
print(isItATriangle(1 , 1, 3))
为什么代码不能正常运行?
而不是
if a + b > c or a + c > b or b + c > a:
return True
else:
return False
右边主要代码展示了这个
if a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True
我如何确定我在逻辑的哪一部分是错误的?
为了 return 为真,您必须满足 所有 条件,而不仅仅是其中一个。因此,您的代码应该是:
def isItATriangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
return True
else:
return False
print(isItATriangle(1 , 1, 3))
更正和简化:
def isItATriangle(a, b, c):
return a + b > c and a + c > b and b + c > a:
print(isItATriangle(1 , 1, 3))