Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Python Code Example: Circumference and Circular Area

This Python script calculates and displays the circumference and area of a circle based on a user-provided radius.

Code Example

import math

r = int(input("Please enter radius: "))

circumference = 2 * math.pi * r

area = math.pi * pow(r, 2)

print("Circumference: " + repr(round(circumference, 2)))
print("Circular Area: " + repr(round(area, 2)))

Output

Please enter radius: 5
Circumference: 31.42
Circular Area: 78.54

Code Explanation

Importing the math Module

import math
  • Purpose: The math module provides access to mathematical functions like pi and pow, which are essential for our calculations.

Reading the Radius Input

r = int(input("Please enter radius: "))
  • input("Please enter radius: "): Prompts the user to enter the radius of the circle.
  • int(...): Converts the input string to an integer.

Calculating the Circumference

circumference = 2 * math.pi * r
  • Formula: Circumference=2×𝜋×𝑟Circumference=2×π×r
  • math.pi: Provides the value of π (Pi).
  • Multiplication: Computes the circumference using the radius r.

Calculating the Area

area = math.pi * pow(r, 2)
  • Formula: Area=𝜋×𝑟2Area=π×r2
  • pow(r, 2): Computes 𝑟2r2, the square of the radius.
  • math.pi: Multiplies π by the square of the radius to get the area.

Printing the Results

print("Circumference: " + repr(round(circumference, 2)))
print("Circular Area: " + repr(round(area, 2)))
  • round(circumference, 2): Rounds the circumference to 2 decimal places.
  • repr(...): Converts the rounded number to a string for printing.
  • String Concatenation: Combines the text with the calculated values to form a complete message.
  • Output Messages:
    • Circumference: Displays the rounded circumference.
    • Area: Displays the rounded area.