In: Computer Science
One of the advantages that functions provide is that they collect frequently-used sequences of Python statements (for example, the code needed to perform a multiple-step operation) into a single named element; whenever we want to perform that operation, we just invoke (call) the function, and our program will execute the code that is associated with that function name. This avoids needless repetition of (potentially long) blocks of code, but it also makes our code reusable (other programs that we write can import that function and use it themselves) and it isolates change (by restricting the number of places in the code that need to be modified in order to fix bugs or to add additional features to that operation).
Briefly describe TWO (real or hypothetical) examples that demonstrate how functions can improve the “flexibility” of a program by isolating change. For example, you might describe a way in which functions make it much easier to change the behavior of a program to handle new (or updated) requirements or to improve the way in which the program performs a particular task.
To demonstrate how functions make it easier to change the behavior of a program to handle new requirements.
Example 1
Let's assume a large program where we are calling a function named foo around 1000 times. The function takes two input values and returns the sum of the two values. But now let's say we want the function to return the multiplication of two numbers instead of their sum. We can just simply edit the function which is just 1 line change in the codebase. If we haven't used the function we would have to make changes in every line where we were supposed to use the function
Look at the code below for a better understanding
def foo(a, b):
return a+b
x = foo(2, 3)
y = foo(5, 7)
z = foo(8, 9)
v = foo(1, 2)
def foo(a, b):
return a*b
x = foo(2, 3)
y = foo(5, 7)
z = foo(8, 9)
v = foo(1, 2)
Example 2
Now let's consider one more situation where we have a program where a function named foo is defined which currently takes two input parameters and returns the sum of the values. But now we require the sum of not two but 3 or more values. We can change the foo function which will take a variable number of arguments and returns their sum.
Look at the above code for a better understanding
def foo(a, b):
return a + b
x = foo(1, 2)
y = foo(5, 7)
z = foo(3, 4)
print(x)
print(y)
print(z)
def foo(*args):
sum = 0
for val in args:
sum += val
return sum
x = foo(1, 2, 3, 4)
y = foo(1, 2, 3)
z = foo(3, 4)
print(x)
print(y)
print(z)
This code will return the sum of any number of input arguments. Thus changing the behavior of the code.