Functions

Sometimes what we have to do is to write long and complex solutions to solve our problems and without the help of functions the task will be really complicated. In order to manage the complexity of a large problem, we have to broke it down into smaller subproblems.

That's exactyl what functions are doing for us. The large program is divided into manageable pieces called program routines for us we focus particularly functions.

We have been using some built-in function such as range and len, but now we will implement our own functions to make things less complex.

  • A routine is named group of instructions performing some task.
  • A routine can be invoked(called) as many times as needed.
  • A function is Python's version of a program routine.
  • Some functions are designed to return a value, while other are designed for other purposes.

def average(n1, n2, n3): # Function Header
    # Function Body
    res = (n1+n2+n3)/3.0
    return res
  • def -> Keyword for functions (define)
  • average -> identifier, which is the function's name
  • (n1, n2, n3) -> list of identifiers called formal parameters or simply parameters

When we use functions we call the function with actual arguments which replaces the parameters.

num1 = 10
num2 = 25
num3 = 16

print(average(num1, num2, num3))

In [1]:
def average(n1, n2, n3): # Function Header
    # Function Body
    res = (n1+n2+n3)/3.0
    return res

In [2]:
num1 = 10
num2 = 25
num3 = 16

print(average(num1, num2, num3))


17.0

In [3]:
average(100, 90, 29)


Out[3]:
73.0

In [4]:
average(1.2, 6.7, 8)


Out[4]:
5.3

In [5]:
def power(n1, n2):
    return (n1 ** n2)

print(power(2, 3))


8

In [6]:
2**3


Out[6]:
8

A value-returing function is a program routine called for it's return function like we used in examples above.

def power(n1, n2):
    return n1 ** n2

A non-value-returning function is called not for a returned value, but for its side effects.


In [7]:
val  = power(2,3)
print(val)


8

In [3]:
def displayWelcome():
    print('This program will do this: ')
displayWelcome()


This program will do this: 

Apply It!

Write the Temperature Conversion program again, this time with the help of functions. But this time you will have to print more than one values between given degree to given degree, check the output:

This program will convert a range of temperatures
Enter (F) to convert Fahrenheit to Celsius
Enter (C) to convert Celcius to Fahrenheit

Enter selection: F
Enter starting temperature to convert: 65
Enter ending temperature to convert: 95

  Degrees   Degrees
Fahrenheit  Celsius
    65.0      18.3
    66.0      18.9
    67.0      19.4
      .        .
      .        .
      .        .
    94.0      34.4
    95.0      35.0

Add More


In [ ]: