A first function for triangles - Answers
Q1. Type this code into Python and get it working:
1 #Calculate the area of a triangle from the base and height
2
3 def area_bh(base, height): # This function has two parameters.
4 '''Calculates the area of a triange from the base and height.
5 Requires two float arguments to work and returns a single float.'''
6 area = 0.5 * base * height
7 return area #This is the answer 'returned' from the function
8
9 myBase = float(input('Please enter the base >>> ')) #get the base
10 myHeight = float(input('Please enter the height >>> ')) #get the height
11 triangle = area_bh(myBase, myHeight) #call the function area_bh and pass it two arguments.
12 print(triangle)
Q2. This program asks the user two enter the base and height of a triangle and then prints out the area.
Q3. Single line comments always begin with with a hash symbol.
Q4. You can easily make multi-line comments using treble single quotes or treble double quotes. See lines 4 - 5 for an example.
Q5. A function's 'docstring' is the multi-line comment that all functions should have. It should sat what the function does, what arguments it expects and what it returns.
Q6. An 'argument' is programming jargon for an actual, real piece of data e.g. 17, 14.76, 'David'.
Q7. A 'parameter' is programming jargon for the type of data expected e.g. by a function. The above function needs two parameters for it to work.
Q8. Programmers, books, websites etc will often use the words 'argument' and 'parameter' interchangeably because they are sort of very similar.
Q9. WA float is a number with a fractional part e.g. 45.04 3.14, -8.0
Q10. Line 9 asks the user to input the base. It then converts it into a floating point number. Line 11 asks the user to input the height of the triable. It then converts it into a floating point number. Line 12 passes these two numbers (these 'arguments') to the function definition on line 3 in the same order that the function definition needs the data (i.e. base first and then the height).
Q11. The function calculates the area and then line 7 'returns' this value to the function call on line 11 (the right hand side of the equals sign), where it is stored in the variable 'triangle'.
Q12. To ask the user for the three sides of a triangle and return the length of the perimeter of a triangle:
#Calculate the perimeter of a triangle from the three sides
def per(side1, side2, side3):
'''Calculates the perimeter of a triange from the three sides.
Requires three float arguments to work and returns a single float.'''
perimeter = side1 + side2 + side3
return perimeter #This is the answer 'returned' from the function
print('\nCalculate the perimeter of a triange >>> ')
mySide1 = float(input('Please enter the length of first side >>> '))
mySide2 = float(input('Please enter the length of second side >>> '))
mySide3 = float(input('Please enter the length of third side >>> '))
myPerimeter = per(mySide1, mySide2, mySide3)
print(myPerimeter)