Error in code: TypeError: can't multiply sequence by non-int of type 'float'

Question:

I am using this simple python script that defines two functions that calculate the area and volume of a cylinder, given its radius and height:

import math

def calculate_area(radius):
    area = math.pi * radius ** 2
    return area

def calculate_volume(radius, height):
    volume = calculate_area(radius) * height
    return volume

r = 5
h = "10"
volume = calculate_volume(r, h)
print("The volume of the cylinder is:", volume)

When I execute the script, I see the following error:
TypeError: can’t multiply sequence by non-int of type ‘float’

I have tried Importing the float() function instead of the math module, but it only gives more errors. can somebody help me with this? Thanks.

Asked By: Kirs

||

Answers:

The ‘h’ variable in your code is defined as a string rather than a number.
You must first use the float() function to convert the h variable to a number before passing it to the calculate_volume() function:

import math

def calculate_area(radius):
    area = math.pi * radius ** 2
    return area

def calculate_volume(radius, height):
    volume = calculate_area(radius) * height
    return volume

r = 5
h = "10"
volume = calculate_volume(r, float(h))
print("The volume of the cylinder is:", volume)
Answered By: Alon Alush

Your h is a str (so it’s a sequence actually) and your calculated area is a float, so python cannot multiply them. Your h should be an int/float.

import math

def calculate_base_area(radius:float)->float:
    area = math.pi * radius ** 2
    return area

def calculate_volume(*,radius: float, height:float)->float:
    volume = calculate_base_area(radius) * height
    return volume

r = 5
h = 10
volume = calculate_volume(radious=r,height=h)
print("The volume of the cylinder is:", volume)

Side notes

  • calculate area does not calculate area of the cyllinder, rather its base area, so I’d suggest renaming to avoid confusion later on. The area would be 2*pi*r*h+2*pi*r**2 (side area+2 base areas)
  • use type hints, this will make your IDE tell you about this kind of mistakes before running the code
  • when the order of the parameters matters it’s good to enforce using keyword arguments in your function (this will prevent using height and radious interchangeably which would lead to errors)
  • if invalid arguments can be passed to your function use try...carch inside to handle that
Answered By: Gameplay

your h is string , for that not working.

Answered By: Amir.q.a
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.