Exercises on Functions

Nelson

2/5/2020

Ex1

Create a function, quad(a,b,c,x), to evaluate a quadratic polynomial at a given value of x. The parameters of the function are, in order:

  1. a, the coefficient of the quadratic term.

  2. b, the coefficient of the linear term.

  3. c, the constant term.

  4. x, the value at which the polynomial is to be evaluated. This polynomial in standard form is written as:

\[ax^2+bx+c\]

Your function should be fruitful. Test your function with a = 1, b = -7, c = 12.

Use the following values of x: 1,2,3,4,5 for testing.

Answer

def quad(a,b,c,x):
    result = a*x**2 + b*x + c
    return result

res = quad(1, -7, 12, 1)  
print(res)
## 6
res = quad(1, -7, 12, 2)  
print(res)
## 2
res = quad(1, -7, 12, 3)  
print(res)
## 0
res = quad(1, -7, 12, 4)  
print(res)
## 0
res = quad(1, -7, 12, 5)  
print(res)
## 2

Ex2

Repeat the exercise above, but make your function, quadv(a,b,c,x), void. Within the function print out the values of all of the variables with identifying text.

Answer

def quadv(a,b,c,x):
    result = a*x**2 + b*x + c
    print("a is",a)
    print("b is",b)
    print("c is",c)
    print("x is",x)
    print("")
    print("The result is",result)
    
quadv(1,-7,12,1)    
## a is 1
## b is -7
## c is 12
## x is 1
## 
## The result is 6