Python Forum
NameError: name 'pi' is not defined - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: NameError: name 'pi' is not defined (/thread-42451.html)



NameError: name 'pi' is not defined - katebishop - Jul-15-2024

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:
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


RE: NameError: name 'pi' is not defined - menator01 - Jul-15-2024

Hope it helps

def calc(shape, arg1, arg2=None):
    pi = 3.14
    if shape == 'square':
        return f'Square: {arg1*arg1}'

    elif shape == 'rectangle':
        return f'Rectangle: {(2*arg1) + (2*arg2)}'

    elif shape == 'circle':
        return f'Circle: {pi * arg1**2}'

    else:
        return 'Error! Wrong shape'


print(calc('square', 8))
print(calc('rectangle', 5,3))
print(calc('circle', 4))
output
Output:
Square: 64 Rectangle: 16 Circle: 50.24



RE: NameError: name 'pi' is not defined - Pedroski55 - Jul-15-2024

math is a good module for calculating things!

import math

print( math.pi )
Or numpy:

from numpy import pi

print(pi)
I think both modules just define pi to a reasonable number of decimal places.

But if you use the module gmpy2 you can get any number of decimal places and finally read the secret message that God coded into the number pi!

Let me know when you have it decoded please!