40.9k views
4 votes
Write a Python program to calculate the area of circle and square. Take the input from user and

display the output.

1 Answer

7 votes

Let's break this down step-by-step. Our program will:

1. Ask the user what they want to calculate the area for: a circle or a square.

2. Based on the user's response, it'll ask for either the radius (for a circle) or the side length (for a square).

3. The program will then calculate and print the area.

Here's how you might write this in Python:

```

import math

def calculate_area(shape):

if shape == 'circle':

radius = float(input('Enter the radius of the circle: '))

area = math.pi * radius * radius

elif shape == 'square':

side = float(input('Enter the length of the side of the square: '))

area = side * side

else:

print('Invalid shape')

return

print(f'The area of the {shape} is {area}')

shape = input('Enter the shape to calculate area (circle or square): ').lower()

calculate_area(shape)

```

Here's what this code is doing:

1. It first imports the `math` module, which contains a lot of mathematical functions and constants, including `pi`, which we need to calculate the area of a circle.

2. The `calculate_area` function takes a string `shape` as its parameter.

- If the shape is a 'circle', it prompts the user to input the radius. It then calculates the area of the circle using the formula `πr^2` and assigns it to the `area` variable.

- If the shape is a 'square', it prompts the user to input the side length. It then calculates the area of the square using the formula `side^2` and assigns it to the `area` variable.

- If the shape is neither a 'circle' nor a 'square', it prints 'Invalid shape' and exits the function.

- Finally, it prints the area of the shape.

3. Outside the function, the program prompts the user to input the shape. It then converts the input to lower case (to handle case differences) and passes it to the `calculate_area` function.

This program covers the basics but there's no error checking to ensure the user enters a valid number. If you need to handle that, you can add a try-except block around the places where you convert the user's input to a float. That way, if they enter something that can't be converted, the program will print a nice error message instead of crashing.

User Keyur
by
8.1k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.