【问题标题】:Trying to write code but getting TypeError: unsupported operand type(s) for +: 'float' and 'type'尝试编写代码但得到 TypeError: unsupported operand type(s) for +: 'float' and 'type'
【发布时间】:2021-03-08 00:20:23
【问题描述】:

这是我正在打印的代码,但出现错误。类型错误:+ 的不支持的操作数类型:'float' 和 'type'

import math

def circles_of_radius():
    #Prints out circumference and area with the ranged radius
     for x in range(3,7):
         C = (2 * math.pi * x) #calculates circumference
         A = (math.pi * x**2) #calculates area
         print(("A circle with radius", x) +str ("has circumference", C) +str (" and area", A))

【问题讨论】:

  • 你能以清晰的方式重新添加你的代码吗?
  • 我认为如果您删除元组括号并将+str 替换为, ,它将起作用。所以,应该是print("radius", x, "circ", C, "area", A)。

标签: python python-3.x


【解决方案1】:

您可以使用F字符串打印值。

print(f"A circle with radius {x} has circumference {C} and area {A}")

输出

A circle with radius3has circumference 18.84955592153876 and area 28.274333882308138
A circle with radius4has circumference 25.132741228718345 and area 50.26548245743669
A circle with radius5has circumference 31.41592653589793 and area 78.53981633974483
A circle with radius6has circumference 37.69911184307752 and area 113.09733552923255

【讨论】:

  • 我需要在代码中的其他任何地方添加 F 字符串还是仅在末尾添加。因为它出现了一个 SyntaxError
  • 就在最后。我可以运行您的代码而不会出现任何错误。
【解决方案2】:

这是你的代码:

import math
def circles_of_radius():
    for x in range(3,7):
        C = (2 * math.pi * x)
        A = (math.pi * x**2)
        print(("A circle with radius",x) + str("has circumference",X) + str (" and area", A))

我建议用那个替换打印:(注意,会在打印中添加一个空格)

print("A circle with radius" , str(x), "has circumference", str(X), "and area", str(A))

或(请注意,使用“+”您需要在消息前后添加空格)

    print("A circle with radius " + str(x) + " has circumference " + str(X) + " and area "+ str(A))

在您的情况下,您将浮点数添加到字符串,然后使用 str() 方法将其转换为字符串

【讨论】:

    【解决方案3】:

    您应该只将数值传递给 str。

    print("A circle with radius "+str(x)+" has circumference "+str(C)+" and area "+str(A))
    

    但是,使用 f 字符串可能会更好/更容易。

    print(f"A circle with radius {x} has circumference {C} and area {A}")
    

    你可能也想把圆周和面积弄圆。

     print(f"A circle with radius {x} has circumference {round(C,2)} and area {round(A,2)}")
    

    【讨论】:

    • 感谢这有助于使用 print("半径为 "+str(x)+" 的圆的周长 "+str(C)+" 和面积 "+str(A))
    猜你喜欢
    • 2020-10-01
    • 2018-11-30
    • 2017-07-17
    • 2020-04-04
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2016-08-30
    • 2023-04-02
    相关资源
    最近更新 更多