Area/Volume Calculator in Python.
About the project: This will be self-contained script that can calculate the area of 2D shapes and the volume of 3D shapes.
The program will present a menu of shapes to choose from. After you select a shape, it will prompt you for the necessary dimensions, calculate the result, and display it.
Area/Volume Calculator:
This Python script is a complete and interactive calculator.
It guides you through a menu to select whether you want to calculate the area or volume, then prompts for the specific shape and its dimensions.
The script will perform the calculation and display the result before returning to the main menu.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# area_volume_calculator.py
import math
def get_numeric_input(prompt, min_value=0):
"""
Helper function to get a valid positive numeric input from the user.
"""
while True:
try:
value = float(input(prompt).strip())
if value <= min_value:
print("Please enter a positive value.")
else:
return value
except ValueError:
print("Invalid input. Please enter a number.")
def calculate_area():
"""
Calculates the area of various 2D shapes.
"""
print("\n--- Area Calculator ---")
print("1. Square")
print("2. Rectangle")
print("3. Circle")
print("4. Triangle")
area_choice = input("Enter your choice (1-4): ").strip()
if area_choice == '1': # Square
side = get_numeric_input("Enter the side length of the square: ")
area = side ** 2
print(f"\nThe area of the square is: {area:.2f}")
elif area_choice == '2': # Rectangle
length = get_numeric_input("Enter the length of the rectangle: ")
width = get_numeric_input("Enter the width of the rectangle: ")
area = length * width
print(f"\nThe area of the rectangle is: {area:.2f}")
elif area_choice == '3': # Circle
radius = get_numeric_input("Enter the radius of the circle: ")
area = math.pi * (radius ** 2)
print(f"\nThe area of the circle is: {area:.2f}")
elif area_choice == '4': # Triangle
base = get_numeric_input("Enter the base length of the triangle: ")
height = get_numeric_input("Enter the height of the triangle: ")
area = 0.5 * base * height
print(f"\nThe area of the triangle is: {area:.2f}")
else:
print("Invalid choice. Please choose from 1, 2, 3, or 4.")
def calculate_volume():
"""
Calculates the volume of various 3D shapes.
"""
print("\n--- Volume Calculator ---")
print("1. Cube")
print("2. Cylinder")
print("3. Sphere")
volume_choice = input("Enter your choice (1-3): ").strip()
if volume_choice == '1': # Cube
side = get_numeric_input("Enter the side length of the cube: ")
volume = side ** 3
print(f"\nThe volume of the cube is: {volume:.2f}")
elif volume_choice == '2': # Cylinder
radius = get_numeric_input("Enter the radius of the cylinder: ")
height = get_numeric_input("Enter the height of the cylinder: ")
volume = math.pi * (radius ** 2) * height
print(f"\nThe volume of the cylinder is: {volume:.2f}")
elif volume_choice == '3': # Sphere
radius = get_numeric_input("Enter the radius of the sphere: ")
volume = (4/3) * math.pi * (radius ** 3)
print(f"\nThe volume of the sphere is: {volume:.2f}")
else:
print("Invalid choice. Please choose from 1, 2, or 3.")
def main():
"""
Main function to run the Area/Volume Calculator with a menu.
"""
print("--- Python Area/Volume Calculator ---")
while True:
print("\nSelect an option:")
print("1. Calculate Area")
print("2. Calculate Volume")
print("3. Quit")
choice = input("Enter your choice (1, 2, or 3): ").strip()
if choice == '1':
calculate_area()
elif choice == '2':
calculate_volume()
elif choice == '3':
print("Exiting Area/Volume Calculator. Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")
play_again = input("\nPress Enter to return to the main menu or 'q' to quit: ").strip().lower()
if play_again == 'q':
print("Exiting Area/Volume Calculator. Goodbye!")
break
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()