Skip to content

Computer Science · Ch 7 — Functions

Functions

7.2

Functions

In programming, the function is one of the chief means of achieving modularity and reusability. A function can be defined as a named group of instructions that accomplishes a specific task when it is invoked (called).

Two properties make functions powerful:

  • Define once, call many times. Once a function is defined, it can be called again and again from different places in the program simply by writing its name and passing the required parameters (if any — parameters are covered in Section 7.3). The code inside the function is never written out a second time.
  • Functions can call functions. A function may also be invoked from inside another function, not just from the main program.

A programmer is free to define as many functions as the program needs.

The tent program, rewritten with functions

The single-block tent-pricing program of Section 7.1 becomes far cleaner when each sub-task is placed in its own user defined function:

# Cost of the tent, written WITH user defined functions

# function definition
def cyl(h, r):
    area_cyl = 2 * 3.14 * r * h    # curved surface area of the cylinder
    return area_cyl

# function definition
def con(l, r):
    area_con = 3.14 * r * l        # curved surface area of the cone
    return area_con

# function definition
def post_tax_price(cost):
    # net payable amount for the tent, including 18% tax
    tax = 0.18 * cost
    net_price = cost + tax
    return net_price

print("Enter the dimensions of the cylindrical part in metres:")
h = float(input("Height: "))
r = float(input("Radius: "))
csa_cyl = cyl(h, r)                            # function call

l = float(input("Slant height of the conical part in metres: "))
csa_con = con(l, r)                            # function call

# canvas needed to make the tent
canvas = csa_cyl + csa_con
print("Area of canvas:", canvas, "sq. m")

rate = float(input("Cost of 1 sq. m of canvas in rupees: "))
total = rate * canvas
print("Total cost of canvas before tax:", total)

print("Net amount payable (including tax):", post_tax_price(total))
``` …