Jul-15-2024, 02:59 AM
(This post was last modified: Jul-15-2024, 10:09 AM by deanhystad.)
I'm working on a Python program to calculate the area of different shapes (square, rectangle, and circle). I've written the code for squares and rectangles, but I'm stuck on the circle part. Here's what I have so far:
Can you help me fix the code so it calculates the circle area correctly using the mathematical constant pi (approximately 3.14159)?
Wordle Unlimited
def calculate_area(shape, side1, side2=None): """Calculates the area of a square or rectangle.""" if shape == "square": return side1 * side1 elif shape == "rectangle": return side1 * side2 else: print("Invalid shape. Please enter 'square' or 'rectangle'.") return None # Example usage for square and rectangle area_square = calculate_area("square", 5) area_rectangle = calculate_area("rectangle", 3, 4) print("Area of square:", area_square) print("Area of rectangle:", area_rectangle) # Now trying to add circle functionality def calculate_circle_area(radius): """Calculates the area of a circle.""" # Here's where I'm stuck! # I know the formula for circle area is pi * radius^2, # but I'm getting an error "NameError: name 'pi' is not defined". return radius * radius # This line causes the error # Trying to call the circle function # circle_area = calculate_circle_area(7) # This line would also cause an error # print("Area of circle:", circle_area)The code throws a
NameError: name 'pi' is not defined
error when trying to calculate the circle area.Can you help me fix the code so it calculates the circle area correctly using the mathematical constant pi (approximately 3.14159)?
Wordle Unlimited