× Introduction Working with Python Basics Data Types Control statements Loops Functions Lists Tuples Strings Turtle eBooks

Functions (divide programs into parts)

Functions are reusable code blocks that will only execute when called. They allowdevelopers to divide their scripts into smaller parts that are easier to understand and reuse.Oncedefined, a function can be called repeatedly fromdifferent places of the program without writing all thecodes of that function every time, or it can be called frominside another function, by simply writing the name ofthe function and passing the required parameters, ifany.

A function is a group of statements that exist within a program for the purpose of performing a specific task.

The Advantages of Function:

• Increases readability, particularly for longer code as by using functions, the program is better organised and easy to understand.

• Reduces code length as same code is not required to be written at multiple places in a program. This also makes debugging easier.

• Increases reusability, as function can be called from another function or another program. Thus, we can reuse or build upon already defined functions and avoid repetitions of writing the same piece of code.

• Work can be easily divided among team members and completed in parallel.

Some of built-in functions:

input(), print(), type() , int(), max(), min(), len() etc.

User Defined Functions:

In addition to the standard library functions, we can define our own functions whilewriting the program. Such functions are called user defined functions. Thus, a function defined to achieve some task as per the programmer's requirement is called a user defined function.

Creating User Defined Function:

Example:

def functionName(list of parameters):                 # Function header
  # Function body
  statement(s)                                                                  
  [return ]

Defining and Calling a Function:

To create a function, you write its definition. Here is the general format of a function definitionin Python:

Function definition (specifies what a function does)

Example:

def functionName():
   statement
   statement
   etc.

def message():
    print("Hello world!")
    print("Welcome to Python")

Function call(Calling a function executes the code in the function)

When a function is called, the interpreter jumps to that function and executes the statements in its block. Then, when the end of the block isreached, the interpreter jumps backto the part of the program that called the function, and the program resumes execution atthat point. When this happens, we say that the function returns.

Example:

functionName()
message()

Argument and Parameter:

The parameter is variable in the declaration of a function. The argument is the actual value of this variable that gets passed to function when the function is called.

Example:

def sum (a, b):    # function definition, a,b are parameters
    return a+b

sumValue = sum(8, 6)   #function call 8,6 are arguments

Note: i) A function argument can also be an expression, such as sum(num+5,num+3).

ii) The parameters should be in the same order as that of the arguments.

Default Parameter:

Python allows assigning a default value to the parameter. A default value is a value that is predefined and assigned to the parameter when the function call does not have its corresponding argument.

The default parameters must be the trailing parameters in the function header that means if any parameter is having default value then all the other parameters to its right must also have default values.

Example:

def calcInterest(rate, principal = 1000, time = 5)

Void Functions and Value-Returning Functions:

void function, simply executes the statements itcontains and then terminates. A value-returning function, executes thestatements that it contains, then returns a value back to the statement that called it.

Void Function Example:

def message():
  print(“Hello world!”)
  print(“Welcome to Python”)

Value-Returning Function Example:

    def sum (a, b):
       return a+b

    sumValue = sum(8, 6)

Scope of a Variable:

A variable defined inside a function cannot be accessed outside it. Every variable has a well-defined accessibility. The part of the program where a variable is accessible can be defined as the scope of that variable.

A variable can have one of the following two scopes: A variable that has global scope is known as a global variable and a variable that has a local scope is known as a local variable.

A) Global Variable: In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any functions defined onwards. Any change made to the global variable will impact all the functions in the program where that variable can be accessed.

(B) Local Variable: A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes.

Python Standard Library

Python has a very extensive standard library. It is a collection of many built in functions that can becalled in the program as and when required, thus saving programmer’s time of creating those commonly used functions everytime.

Built-in functions:

Built-in functions are the ready-made functions in Python that are frequently used in programs.

Let us inspect the following Python program:

#Program to calculate square of a number
a = int(input("Enter a number: ")
b = a * a
print(" The square of ",a ,"is", b)

In the above program input(), int() and print() are the built-in functions. The set of instructions to be executed for these built-in functions are already defined in the python interpreter.

Commonly used built-in functions

Function Syntax Arguments Returns Example Output
abs(x) x may be an integer or floating point number Absolute value of x >>> abs(4)
4
>>> abs(-5.7)
5.7
divmod(x,y) x and y are integers A tuple: (quotient, remainder) >>> divmod(7,2)
(3, 1)
>>> divmod(7.5,2)
(3.0, 1.5)
>>> divmod(-7,2)
(-4, 1)
max(sequence) or max(x,y,z,...) x,y,z,.. may be integer or floating point number Largest number in the sequence/ largest of two or more arguments >>>max([1,2,3,4])
4
>>>max("Sincerity")
'y' #Based on ASCII value
>>>max(23,4,56)
56
min(sequence) or min(x,y,z,...) x,y,z,.. may be integer or floating point number Smallest number in the sequence/ smallest of two or more arguments >>>max([1,2,3,4])
1
>>>max("Sincerity")
'S' #Uppercase letters have lower ASCII values than lowercase letters.
>>>max(23,4,56)
4
pow(x,y[,z]) x, y, z may be integer or floating point number xy (x raised to the power y) if z is provided, then: (xy ) % z >>>pow(5,2)
25
>>>pow(5.3,2.2)
39.2
>>> pow(5,2,4)
1
sum(x[,num]) x is a numeric sequence and num is an optional argument Sum of all the elements in the sequence from left to right. if given parameter, num is added to the sum >>> sum([2,4,7,3])
16
>>>sum([2,4,7,3],3)
19
>>>sum((52,8,4,2))
66
len(x) x can be a sequence or a dictionary Count of elements in x >>>len(“Patience”)
8
>>>len([12,34,98])
3
>>>len((9,45))
2

Module

Other than the built-in functions, the Python standard library also consists of a number of modules. While a function is a grouping of instructions, a module is a grouping of functions. As we know that when a program grows, function is used to simplify the code and to avoid repetition. For a complex problem, it may not be feasible to manage the code in one single file. Then, the program is divided into different parts under different levels, called modules. Also, suppose we have created some functions in a program and we want to reuse them in another program. In that case, we can save those functions under a module and reuse them.A module is created as a python (.py) file containing acollection of function definitions.

To use a module, we need to import the module. Once we import a module, we can directly use all the functions of that module. The syntax of import statement is as follows:

import modulename1 [,modulename2, …]

This gives us access to all the functions in the module(s). To call a function of a module, the function name should be preceded with the name of the module with a dot(.) as a separator.

The syntax is as shown below:

modulename.functionname()

Built-in Math module:

It contains different types of mathematical functions. Most of the functions in this module return a float value. In order to use the math module we need to import it using the following statement:

import math

Commonly used functions in math module

Function Syntax Arguments Returns Example Output
math.ceil(x) x may be an integer or floating point number ceiling value of x >>> math.ceil(-9.7)
-9
>>>math.ceil (9.7)
10
>>>math.ceil (9)
9
math.floor(x) x may be an integer or floating point number floor value of x >>> math.floor(-4.5)
-5
>>> math.floor(4.5)
4
>>> math.floor(4)
4
math.fabs(x) x may be an integer or floating point number absolute value of x >>>math.fabs(6.7)
6.7
>>>math.fabs(-6.7)
6.7
>>>math.fabs(-4)
4.0
math.factorial(x) x is a positive integer factorial of x >>>math.factorial(5)
120
math.fmod(x,y) x and y may be an integer or floating point number x % y with sign of x >>> math.fmod(4,4.9)
4.0
>>>math.fmod(4.9,4.9)
0
>>>math.fmod(-4.9,2.5)
-2.4
math.gcd(x,y) x, y are positive integers gcd (greatest common divisor) of x and y >>> math.gcd(10,2)
2
math.pow(x,y) x, y may be an integer or floating point number xy (x raised to the power y >>>math.pow(3,2)
9.0
>>>math.pow(4,2.5)
32.0
math.sqrt(x) x may be a positive integer or floating point number square root of x >>>math.sqrt(144)
12.0
>>>math.sqrt(.64)
0.8
math.sin(x) x may be an integer or floating point number in radians sine of x in radians >>>math.sin(0)
0
>>>math.sin(6)
-0.279

Module name : random

This module contains functions that are used for generating random numbers. For using this module, we can import it using the following statement:

import random

Commonly used functions in random module

Function Syntax Arguments Returns Example Output
random.random() No argument (void) Random Real Number (float) in the range 0.0 to 1.0 >>> random.random()
0.65333522
random. randint(x,y) x, y are integers such that x <= y Random integer between x and y >>>random.randint(3,7)
5
>>>random.randint(-3,5)
3
>>>random.randint(-5,-3)
-5.0
random. randrange(y) y is a positive integer signifying the stop value Random integer between 0 and y >>>random.randrange(5)
4
random. randrange(x,y) x and y are positive integers signifying the start and stop value Random integer between x and y >>>random.randrange(2,7)
2

Module name : statistics

This module provides functions for calculating statistics of numeric (Real-valued) data. It can be included in the program by using the following statements:

import statistics

Some of the function available through statistics module

Function Syntax Arguments Returns Example Output
statistics.mean(x) x is a numeric sequence arithmetic mean >>> statistics. mean([11,24,32,45,51])
32.6
statistics.median(x) x is a numeric sequence median (middle value) of x >>>>statistics. median([11,24,32,45,51])
32
statistics.mode(x) x is a sequence mode (the most repeated value) >>>statistics. mode([11,24,11,45,11])
11

Note:

• import statement can be written anywhere in the program

• Module must be imported only once

• In order to get a list of modules available in Python, we can use the following statement: >>> help("module")

• To view the content of a module say math, type the following: >>> help("math")

• The modules in the standard library can be found in the Lib folder of Python.

From Statement

Instead of loading all the functions into memory by importing a module, from statement can be used to access only the required functions from a module. It loads only the specified function(s) instead of all the functions in a module.

Its syntax is
>>> from modulename import functionname [, functionname,...]

To use the function when imported using "from statement" we do not need to precede it with the module name. Rather we can directly call the function as shown in the following examples:

>>> from random import random
>>> random() #Function called without the module name
 Output: 
0.9796352504608387
>>> from math import ceil,sqrt
>>> value = ceil(624.7)
>>> sqrt(value)
Output: 
25.0

Example Programs

1.Write a Python program to get the three test scores, calculate their average test score and congratulate if the average is greater than 95.

# define HIGH_SCORE constant
HIGH_SCORE = 95
# Get the three test scores
test1 = float(input('Enter the score for test 1: '))
test2 = float(input('Enter the score for test 2: '))
test3 = float(input('Enter the score for test 3: '))
# Calculate the average test score.
average = (test1 + test2 + test3) / 3

# Print the average.
print('The average score is', round(average,2))

# If the average is a high score,
# congratulate the user.
if average >= HIGH_SCORE:
    print('Congratulations!')
    print('That is a great average!')

OUTPUT:
Enter the score for test 1: 96.5
Enter the score for test 2: 97.0
Enter the score for test 3: 98.0
The average score is 97.17
Congratulations!
That is a great average!