back

A simple menu structure to call different functions - 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)

Back