Search code examples
pythontypeerror

I have function with another function inside. It gives me Type Error (Python)


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()

This is my code, and I have error:

  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'

I understand what the error means, but I can't figure out how to fix this. If someone can give me a tip I'll be grateful.


Solution

  • You are getting this error because you did not specify a return value in circle, and the default return value of a function in Python is None. You need to add a return statement to your circle function, like this:

    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()
    

    But, you could also return the value directly without creating a variable for that. Additionally, you should use math.pi instead of 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()