Back

A function for circles

circle
Q1.
Get the following Python program working:

PI = 3.14

#Calculate the area of a circle
def area_circle(radius):
    area = PI * radius * radius
    return area

myRadius = float(input('Please enter the radius of the circle >>> '))
units = input('What units are you using >>> ')
print('The area of the circle is',round(area_circle(myRadius),2),units,'squared')

Q2. Describe what this program does.
Q3. Why is PI in capital letters?
Q4. How many parameters does the function area_circle require to work?
Q5. Which keyword is used to round the answer to two decimal places?
Q6. What error message do you get if you call the function with zero or with two arguments?
Q7. What is the maths formula that works out the perimeter of a circle with a radius r?
Q8. Write a function that prints out the perimeter of the circle as well as the area. Call the functions and check it works correctly. To do this, you must predict the answers before running the code.
Q9. Add appropriate docstrings to both your functions.
Q10. Modify your code so your user is given a menu that asks them whether they want to calculate the perimeter, or the area, or both values, and then displays only what the user has asked for. Don't forget to display appropriate units!
Q11. Functions return only one value. If we make that value a tuple, however, we can return more than one value. Get this code working:

import math
def circles(rad):
""" Return (circumference, area) of a circle with radius rad """
    cir = 2 * math.pi * rad
    area = math.pi * rad * rad
    return (cir, area)

print(circles(3))

Q12. How can you access each value returned as a tuple from a function? Get this code working. 

import math
def circles(rad):
""" Return (circumference, area) of a circle with radius rad """
    cir = 2 * math.pi * rad
    area = math.pi * rad * rad
    return (cir, area)

temp = circles(3)
print('Circumference is',temp[0])
print('Radius is',temp[1])

Back