LambdaLabTM
Computer Science · Class 11 · Sample Programs
Sample programTwo answers⏱️ 7 min read

Area & Circumference of a Circle

The problem: the user gives the radius of a circle. Display its area and its circumference. One input, two outputs — and the first program where a constant like π earns a box of its own.

1Plan it first

Input
what we ask the user for
  • the radius, r
Process
what we work out
  • area = pi * r * r
  • circumference = 2 * pi * r
Output
what we show
  • the area
  • the circumference

The formulae are the ones from your maths book: area = πr² and circumference = 2πr. Everything else is translation.

2The program

circle.py
# area and circumference of a circle

pi = 3.14159

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

area = pi * r * r
circumference = 2 * pi * r

print('Area =', area)
print('Circumference =', circumference)
Output
Enter the radius of the circle: 7
Area = 153.93791
Circumference = 43.98226

Try it with a radius of your own:

circle.py

3Why π gets a box of its own

You could type 3.14159 straight into both formulae. Putting it in a variable first is better for three reasons, and they apply to every constant you ever use:

It is written once

Type 3.14159 twice and you can mistype it once. The program would still run, with two answers that disagree.

It changes in one place

Want more decimal places? Edit the first line. Both formulae follow automatically.

It reads as maths

pi * r * r says πr². 3.14159 * r * r makes the reader work out what the number is.

How many decimal places of π?
3.14159 is plenty for school work, and 3.14 is accepted too — with a radius of 7 they differ by less than a tenth of a square unit. What matters in an exam is that the value you used is written in the program, on its own line, where the examiner can see it.

4Three ways to write r²

All three of these mean the same thing, and you will see all three in textbooks:

squares.py
r = 7

print(pi * r * r)     # multiply it out
print(pi * r ** 2)    # the power operator
print(pi * pow(r, 2)) # the pow() function

r * r is the clearest for a square. ** is what you want for cubes and higher, where writing it out gets silly. Watch the precedence though: ** runs before *, so pi * r ** 2 squares r first, exactly as intended.

5Now you try

  1. Change pi to 3.14 and run it again. How much does the area move?
  2. Add the diameter (2 * r) to the output.
  3. Ask for the diameter instead of the radius, and work the radius out from it.
your_turn.py

6Recap

Key Takeaway
One input() can feed as many calculations as you like. Keep constants like π in a variable at the top, use float() because a radius may have decimals, and give each answer its own print() with a label so the user knows which is which.
Quick Check

Why is float() used for the radius rather than int()?

Quick Check

What does pi * r ** 2 calculate when r is 7?