back

A function for circles - Answers

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. This program asks the user for the radius of a circle and then prints out the area.
Q3. By convention, constants in Python are in capital letters.
Q4. The function area_circle requires just one parameter to work.
Q5. The 'round' keyword is used to round the answer to two decimal places.
Q6. You may get an error message about being unable to convert a string.
Q7. The maths formula that works out the perimeter of a circle with a radius r is 2 * pi * r.
Q8 - Q10 To 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.

PI = 3.14

#Calculate the area of a circle
def area_circle(radius):
    '''This function works out the area of a circle. It
    requires one float to work and will return one float.
    '''
    area = PI * radius * radius
    return area

#Calculate the perimeter of a circle
def per_circle(radius):
    '''This function works out the perimeter of a circle. It
    requires one float to work and will return one float.
    '''
    perimeter = 2 * PI * radius
    return perimeter


myRadius = float(input('Please enter the radius of the circle >>> '))
units = input('What units are you using >>> ')
choice = input('''

Press 'a' for the area
Press 'p' for the perimeter
Press 'b' for both
'''
)
if choice == 'a':
    print('The area of the circle is',round(area_circle(myRadius),2),units,'squared')
elif choice == 'p':
    print('The perimeter of the circle is',round(per_circle(myRadius),2),units)
else:
    print('\nThe area of the circle is',round(area_circle(myRadius),2),units,'squared')
    print('\nThe perimeter of the circle is',round(per_circle(myRadius),2),units)

Q11. This function returns one data structure; it is a tuple containing multiple values.

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 from a function in a tuple? 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])

As you can see, you first of all store the tuple returned from the function. Then you access each element in the normal way, by refering to each element's index.

Back