首页 > 解决方案 > 继续获取 TypeError: unsupported operand type(s) for *=: 'function' and 'float' error for pythagorean Triplet

问题描述

我一直在尝试编写一个代码来推断直角三角形是否是毕达哥拉斯三元组。然后我尝试在海龟中绘制三角形。但是,当我尝试获得底边和斜边之间的度数时,我得到了:

TypeError: unsupported operand type(s) for *=: 'function' and 'float'

这是我的代码:

   import math
   isrightangled = int(input('is your triangle right-angled? enter 1 for no. if it is, press any other number'))
   if isrightangled == 1:
       print('your triangle is not a pythagorean triplet.')
   else:
       a = int(input('Please enter the perpendicular height of your triangle.'))
       b = int(input('please enter the base length of your triangle.'))
       apowerof2 = a * a
       bpowerof2 = b * b
       cpowerof2 = apowerof2 + bpowerof2
       c = math.sqrt(cpowerof2)
       degrees = int(math.degrees(math.atan(a/b)))
       print(degrees)
       cinput = int(input('Please enter the length of the hypotenuse of the triangle.'))
       if c == cinput:
           print ('your triangle is a pythagorean triplet')
           from turtle import *
           drawing_area = Screen()
           drawing_area.setup(width=750, height=900)
           shape('circle')
           left(90)
           forward(a * 100)
           backward(a*100)
           right(90)
           forward(b*100)
           left(degrees)
           forward(c*100)
           done()
       else:
           print ('your triangle is not a pythagorean triplet.')

任何帮助将不胜感激!

标签: pythonturtle-graphics

解决方案


问题是度数变量的名称,它与turtle.degrees() 函数冲突。(https://www.geeksforgeeks.org/turtle-degrees-function-in-python/

只需更改变量名称

另外,这里有两个注意事项:

  • 无需创建那么多变量来计算 c。你可以写c = math.sqrt(a * a + b * b)
  • left(degrees)还不够,你需要做left(180-degrees)

这是这些更改后的代码:

import math
from turtle import *
isrightangled = int(input('is your triangle right-angled? enter 1 for no. if it is, press any other number'))
if isrightangled == 1:
    print('your triangle is not a pythagorean triplet.')
else:
    a = int(input('Please enter the perpendicular height of your triangle.'))
    b = int(input('please enter the base length of your triangle.'))
    c = math.sqrt(a * a + b * b)
    degs = int(math.degrees(math.atan(a/b)))
    cinput = int(input('Please enter the length of the hypotenuse of the triangle.'))
    if c == cinput:
        print ('your triangle is a pythagorean triplet')
        drawing_area = Screen()
        drawing_area.setup(width=750, height=900)
        shape('circle')
        left(90)
        forward(a * 100)
        backward(a*100)
        right(90)
        forward(b*100)
        left(180-degs)
        forward(c*100)
        done()
    else:
        print ('your triangle is not a pythagorean triplet.')

推荐阅读