这是我的代码,看起来有点重复,但我想不出一种不同的方法。(顺便说一句,它工作得很好,但在我看来有点“不干净”)
while True:
try:
num1 = int(input("Type in the first parameter: "))
num2 = int(input("Type in the second parameter: "))
num3 = int(input("Type in the third parameter: "))
break
except ValueError:
print("You have to type in a number. ")
while True:
if num1 > num2 and num1 > num3:
c = num1
if c * c == num2 * num2 + num3 * num3:
print("Your triangle is a pythagorean triangle")
else:
print("Your triangle isn't a pythagorean triangle")
elif num2 > num1 and num2 > num3: # c - hypotenuse
c = num2
if c * c == num1 * num1 + num3 * num3:
print("Your triangle is a pythagorean triangle")
else:
print("Your triangle isn't a pythagorean triangle")
elif num3 > num1 and num3 > num2:
c = num3
if c * c == num2 * num2 + num1 * num1:
print("Your triangle is a pythagorean triangle")
else:
print("Your triangle isn't a pythagorean triangle")
elif num1 == num2 and num2 == num3 and num1 == num3:
print("There's no such thing as a pythagorean triangle with all sides the same, try again")
again = str(input("Do you want to continue? [Y/n]\n"))
if again == "Y" or again == "y":
pass
else:
break
发布于 2018-07-23 08:39:31
您可以使用max函数和一些数学知识来减少对if用例的需求。下面的示例没有重复的循环
num1 = int(input("Type in the first parameter: "))
num2 = int(input("Type in the second parameter: "))
num3 = int(input("Type in the third parameter: "))
if num1 == num2 == num3:
print("There are no pythagorean triangle with all sides equal")
exit(1)
c= max(num1,num2,num3)
if c * c == num1 * num1 + num2 * num2 + num3 * num3 - c * c:
print("Your triangle is a pythagorean triangle")
else:
print("Your triangle isn't a pythagorean triangle")
发布于 2018-07-23 08:04:14
您可以很容易地执行num2 < num1 > num3
,而不是编写num1 > num2 and num1 > num3
,它的工作方式是一样的。
另一方面,我会对数字进行排序,不用担心不同的组合:
num1, num2, num3 = sorted( [num1, num2, num3] )
# here the num1 < num2 < num3 so you may use a single check
if num1 * num1 + num2 * num2 == num 3 * num3 : # etc...
https://stackoverflow.com/questions/51470100
复制相似问题