Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to calculate the area of a circle - Python Program

Example 1 :

import math def area_circle(radius): """Return the area of a circle.""" return math.pi * radius**2 print(area_circle(5))

Output

 
OUTPUT  :
78.53981633974483

Example 2 : Advanced Program

import math def calculate_circle_area(radius): """ Calculates the area of a circle given its radius. Args: radius: A float representing the radius of the circle. Returns: A float representing the area of the circle. """ if radius < 0: raise ValueError("Radius cannot be negative.") area = math.pi * (radius ** 2) return area # Example usage and output if __name__ == "__main__": try: user_radius = float(input("Enter the radius of the circle: ")) calculated_area = calculate_circle_area(user_radius) print(f"The area of a circle with radius {user_radius} is: {calculated_area:.2f}") except ValueError as e: print(f"Error: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")

Output

 
OUTPUT  :
Enter the radius of the circle: 10
The area of a circle with radius 10.0 is: 314.16

Explanation:

import math:

This line imports the math module, which provides access to mathematical functions and constants, including math.pi for a precise value of pi.

def calculate_circle_area(radius)::

This defines a function named calculate_circle_area that takes one argument, radius.

Docstring:

The triple-quoted string below the function definition is a docstring, which explains what the function does, its arguments (Args), and what it returns (Returns).

Input Validation:

if radius < 0: checks if the provided radius is negative. If it is, a ValueError is raised, preventing calculations with invalid input.

Area Calculation:

area = math.pi * (radius ** 2) calculates the area using the formula A = πr², where math.pi provides the value of pi and radius ** 2 calculates the square of the radius.