【问题标题】:I have function with another function inside. It gives me Type Error (Python) [duplicate]我在里面有另一个功能。它给了我类型错误(Python)[重复]
【发布时间】:2021-11-24 21:28:44
【问题描述】:
def cylinder():
    r = int(input("Radius = "))
    h = int(input("Height = "))
    s = 2 * 3.14 * r * h
    if input("Do you want to know full area? [y/n]: ") == "y":
        s += 2 * circle(r)
    print(s)

def circle(r):
    s1 = 3.14*r*r
cylinder()

这是我的代码,我有错误:

  File "C:\Users\Good dogie\Desktop\python-work\main.py", line 187, in <module>
    cylinder()
  File "C:\Users\Good dogie\Desktop\python-work\main.py", line 182, in cylinder
    s += 2 * circle(r)
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

我了解错误的含义,但我不知道如何解决此问题。如果有人可以给我小费,我将不胜感激。

【问题讨论】:

  • circle() 隐式返回 None

标签: python typeerror


【解决方案1】:

您没有从 circle() 返回值。 当 Circle 运行时,它返回 None。 在代码中添加返回将停止此错误。

def cylinder():
    r = int(input("Radius = "))
    h = int(input("Height = "))
    s = 2 * 3.14 * r * h
    if input("Do you want to know full area? [y/n]: ") == "y":
        s += 2 * circle(r)
    print(s)

def circle(r):
    s1 = 3.14*r*r
    return s1
cylinder()

【讨论】:

  • 为什么要将 s1 转换为 int?
【解决方案2】:

您收到此错误是因为您没有在 circle 中指定返回值,而 Python 中函数的默认返回值是 None。您需要在 circle 函数中添加一个 return 语句,如下所示:

def cylinder():
    r = int(input("Radius = "))
    h = int(input("Height = "))
    s = 2 * 3.14 * r * h
    if input("Do you want to know full area? [y/n]: ") == "y":
        s += 2 * circle(r)
    print(s)

def circle(r):
    s1 = 3.14 * r * r
    return s1

cylinder()

但是,您也可以直接返回该值,而无需为此创建变量。此外,您应该使用math.pi 而不是3.14

import math

def cylinder():
    r = int(input("Radius = "))
    h = int(input("Height = "))
    s = 2 * math.pi * r * h
    if input("Do you want to know full area? [y/n]: ") == "y":
        s += 2 * circle(r)
    print(s)

def circle(r):
    return math.pi * r * r

cylinder()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多