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
- the radius,
r
area = pi * r * rcircumference = 2 * pi * r
- 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
# 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)Enter the radius of the circle: 7 Area = 153.93791 Circumference = 43.98226
Try it with a radius of your own:
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:
Type 3.14159 twice and you can mistype it once. The program would still run, with two answers that disagree.
Want more decimal places? Edit the first line. Both formulae follow automatically.
pi * r * r says πr². 3.14159 * r * r makes the reader work out what the number is.
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:
r = 7
print(pi * r * r) # multiply it out
print(pi * r ** 2) # the power operator
print(pi * pow(r, 2)) # the pow() functionr * 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
- Change
pito3.14and run it again. How much does the area move? - Add the diameter (
2 * r) to the output. - Ask for the diameter instead of the radius, and work the radius out from it.
6Recap
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.Why is float() used for the radius rather than int()?
What does pi * r ** 2 calculate when r is 7?