Funtions Flashcards
BASICS
Define a function //addittion// that takes two numbers and prints the corresponding sum.
def addition(a, b): print("a + b is equal to",str(a + b)) return
#testing the function addition(3,4)
OPTIONAL PARAMETERS
Define a function //addition// that takes either three or two numbers and prints the corresponding sum.
testing the function
def addition(a, b, c = None):
if c == None:
print(“a + b is equal to”,str(a + b))
return
else:
print(“a + b + c is equal to”,str(a + b +c))
return
addition(3,4)
addition(3,4,5)
PREDIFINED PARAMETERS
Define a //get_area// function that computes the area of a rectangle with dimensions a x b. The function should be able to take a third parameter indicating if the result must be calculated in square centimeters or square inches (“cm”, “in”). If the function is invoked only with arguments _a and _b the function should compute the result in square centimeters.
def compute_area(a, b, units = "cm"): if units == "cm": area = a * b print("The rectangle has an area of " + str(area) + " square centimeters.") return
if units == "in": area = a * b print("The rectangle has an area of " + str(area) + " square inches.") return
# testing the function compute_area(2,3) compute_area(2,3, units = "cm") compute_area(2,3, units = "in")