Developing Functions

Let us understand how to develop functions using Python as programming language.

  • Function starts with def followed by function name.

  • Parameters can be of different types.

    • Required

    • Keyword

    • Variable Number

    • Functions

  • Functions which take another function as an argument is called higher order functions.

Tasks

Let us perform few tasks to understand how to develop functions in Python.

  • Sum of integers between lower bound and upper bound using formula.

def sumOfN(n):
    return int((n * (n + 1)) / 2)
sumOfN(10)
55
def sumOfIntegers(lb, ub):
    return sumOfN(ub) - sumOfN(lb -1)
sumOfIntegers(5, 10)
45
  • Sum of integers between lower bound and upper bound using loops.

def sumOfIntegers(lb, ub):
    total = 0
    for e in range(lb, ub + 1):
        total += e
    return total
sumOfIntegers(1, 10)
55
sumOfIntegers(5, 10)
45
  • Sum of squares of integers between lower bound and upper bound using loops.

def sumOfSquares(lb, ub):
    total = lb * lb
    for e in range(lb + 1, ub + 1):
        total += e * e
    return total
sumOfSquares(2, 4)
29
  • Sum of the even numbers between lower bound and upper bound using loops.

def sumOfEvens(lb, ub):
    total = lb if lb % 2 == 0 else 0
    for e in range(lb + 1, ub + 1):
        total += e if e%2==0 else 0
    return total
sumOfEvens(2, 4)
6