Funtions Flashcards

1
Q

BASICS

Define a function //addittion// that takes two numbers and prints the corresponding sum.

A
def addition(a, b):
    print("a + b is equal to",str(a + b))
    return 
#testing the function
addition(3,4)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

OPTIONAL PARAMETERS

Define a function //addition// that takes either three or two numbers and prints the corresponding sum.

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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.

A
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")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly