3.0 Functions

Syllabus

Functions, def Statements with Parameters, Return Values and return Statements, The None Value, Keyword Arguments and print(), Local and Global Scope, The global Statement, Exception Handling, A Short Program: Guess the Number.

3.1 Introduction

A function is a group (or block ) of statements that perform a specific task . Functions run only when it is called.  One can pass data into the function in the form of parameters. Function can also return data as a result. Instead of writing a large program as  one long sequence of instructions, it can be written as several small function, each performing a specific part of the task. They constitute line of code(s) that are executed sequentially from top to bottom by Python interpreter. A python function is written once and is used / called as many time as required. Functions are the most important building blocks for any application in Python and work on the divide and conquer approach. Functions can be conquered into the following three types :

(i) User Defined

(ii) Built in

(iii) Modules

(i) User Defined Functions :

Functions that is defined by programmer to do certain specific task are referred as user-defined functions. The two main components of user defined functions are :

  1. Defining a Function
  2. Calling a Function

1. Defining a function:

Function is defined using def keyword in Python.

def  fun_name(comma_seperated_parameter_ list):
       stmt1
       stmt2 
       stmt3
       -------
       stmtn
       return stmt


Statements below def begin with four spaces. This is called indentation. It is a requirement of Python that the code following a colon must be indented. 

A function definition consists of the following components: 
  1. Keyword def marks the start of  function header
  2. A function name to uniquely identify it. Function naming follows the same rules as rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function . They are optional.
  4. A colon ( : ) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid Python statements that make up the function body. Statements must have same indentation level (usually) 4 spaces.
  7. An optional return statement to return a value from the function .

Example : In the following example a function called cube(n) is defined to compute the cube of any number say n.

          def cube(n): 
             ncube = n**3
             return ncube

2. Calling a Function :

In the above example, we have declared a function named cube(n). Now, to use this function, we need to call it. Here’s how we can call the cube() function in Python.

x = cube(3)

print(x)

In the example illustrated below a function sqrsum (n1,n2 ) is defined to calculate and return the sum of squares of two numbers n1 and n2 . The returned value will be stored in the variable called sqsum by assigning the value obtained by calling the function sqrsum( ).

Parameters and arguments

Parameters are temporary variable names within functions. The argument can be thought of as the value that is assigned to that temporary variable.

  • n‘ here is the parameter for the function ‘cube‘. This means that anywhere we see ‘n‘ within the function will act as a placeholder until number is passed an argument.
  • Here 3 is the argument.
  • Parameters are used in function definition and arguments are used in function call.

Working of function

Types of Functions in Python

1. Function without parameters

2. Function with parameters but without returning values.

3. Function with parameters and return values

4. Function which returns multiple values

3.2 The None-Value

In Python there is a value called None, which represents the absence of a value. None is the only value of the None Type data type. (Other programming languages might call this value null, nil, or undefined.) Just like the Boolean True and False values, None must be typed with a capital N. 

3.3 Keyword Arguments and print()

Keyword arguments are identified by the keyword put before them in the function call. Keyword arguments are often used for optional parameters. For example, the print( ) function has the optional parameters end and sep to specify what should be printed at the end of its arguments and between its arguments (separating them), respectively. Following examples illustrates the behavior of print with end , without end and with sep.

3.4 Local and Global Scope

Parameters and variables that are assigned in a called function are said to exist in that function’s local scope. Variables that are assigned outside all functions are said to exist in the global scope. A variable that exists in a local scope is called a local variable, while a variable that exists in the global scope is called a global variable. A variable must be one or the other; it cannot be both local and global. Following example illustrates the difference between local and global variable .

Local variable cannot be used in the global scope

Consider this program which will cause an error when you run it:

If you run this program the output will look like this

The error happens because the x  variable exists only in the local scope created when fun1() is called. Once the program execution returns from fun1(), that local scope is destroyed, and there is no longer a variable named x. So when your program tries to run print(x), Python gives you an error saying that x is not defined. This makes sense if you think about it; when the program execution is in the global scope, no local scopes exist, so there can’t be any local variables. This is why only global variables can be used in the global scope.

Local Scopes Cannot Use Variables in Other Local Scopes

A new local scope is created whenever a function is called, including when a function is called from another function. Consider this program:

When the program starts the func1() is called and a local scope is created . The local variable x is set to 10. Then fun2() is called and a second local scope is created . Multiple local scopes can exist at the same time . In this new local scope , the local variable y is set to 21 and a  local variable x which is different from the one in fun1()’s local scope is also created and set to 0. When fun2() returns the local scope for the call to fun1() still exists here the x variable is set to 10. This is what the programs prints.

The local variables in one function are completely separate the local variable in another function.

Global Variable Can be read from a local scope :

Consider the following program :

Since there is no parameter named x or any code that assigns x a value in the fun1() function , when x is used in fun1(), Python considers it a reference to the global variable x. This is why 42 is printed when the previous program is run.

Local and Global Variables with the same Name :

One should avoid using local variables that have the same name as a global variable or another local variable. Consider the following program :

When you run the program , it outputs the following :

There are actually three different variables in this program, but confusingly they are all named x.

A variable named x that exists in  a local scope when fun1() is called.

A variable named x that exists in a local scope when fun2() is called

A variable named x that exists in the global scope

Since these three separate variables all have the same name, it can be confusing to keep of which one is being used at any given time . This is why you should avoid using the same variable name in different scopes.

Global Statement

If you need to modify a global variable from within a function, used the global statement . If you have a line such as global x at the top of a function, it tells Python, In this function, x  refers to the global variable, so don’t create a local variable with this name. For example, type the following code  and run

When you run this program the final print() call will output this :

Because x is declared global at the top of spam() , when x is set to ‘spam’ , this assignment is done to the globally scoped x. No local x variable is created.

There are four rules to tell whether a variable is in a local scope or global scope:

1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.

 2. If there is a global statement for that variable in a function, it is a global variable.

3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.

4. But if the variable is not used in an assignment statement, it is a global variable.

Exceptional Handling

Right now, getting an error, or exception, in your Python program means the entire program will crash. You don’t want this to happen in real-world programs. Instead, you want the program to detect errors, handle them, and then continue to run. For example, consider the following program, which has a “divide-byzero” error. Open a new file editor window and enter the following code, saving it as zeroDivide.py:

We’ve defined a function called spam, given it a parameter, and then printed the value of that function with various parameters to see what happens. This is the output you get when you run the previous code:

A ZeroDivisionError happens whenever you try to divide a number by zero. From the line number given in the error message, you know that the return statement in spam() is causing an error.

Try and Except  :

Errors can be handled with try and except statements. The code that could potentially have an error is put in a try clause. The program execution moves to the start of a following except clause if an error happens. You can put the previous divide-by-zero code in a try clause and have an except clause contain code to handle what happens when this error occurs.

When code in a try clause causes an error, the program execution immediately moves to the code in the except clause. After running that code, the execution continues as normal. The output of the previous program is as follows:

Note that any errors that occur in function calls in a try block will also be caught. Consider the following program, which instead has the spam() calls in the try block:

When this program is run, the output looks like this:

The reason print(spam(1)) is never executed is because once the execution jumps to the code in the except clause, it does not return to the try clause. Instead, it just continues moving down as normal.

ii. Built in functions 

Built in functions are the predefined functions that are already available in python. Functions provide efficieincy  and structure to a programming language . python has many useful built in functions to  make programming easier , faster and more powerful.

Some of the important built-in functions are listed below :

abs()   : Returns the absolute value of a number
ascii()	: Returns a readable version of an object. Replaces none-ascii characters with escape character
bin()	: Returns the binary version of a number
bool()	: Returns the boolean value of the specified object
bytearray() :Returns an array of bytes
bytes() : Returns a bytes object
chr(): Returns a character from the specified Unicode code.
classmethod(): Converts a method into a class method
complex():Returns a complex number
delattr(): Deletes the specified attribute (property or method) from the specified object
dict(): Returns a dictionary (Array)
dir(): Returns a list of the specified object's properties and methods
divmod(): Returns the quotient and the remainder when argument1 is divided by argument2
enumerate(): Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval(): Evaluates and executes an expression
filter(): Use a filter function to exclude items in an iterable object
float()	Returns a floating point number
format(): Formats a specified value
getattr(): Returns the value of the specified attribute (property or method)
globals(): Returns the current global symbol table as a dictionary
hex(): Converts a number into a hexadecimal value
id(): Returns the id of an object
input(): Allowing user input
int(): Returns an integer number
isinstance(): Returns True if a specified object is an instance of a specified object
issubclass(): Returns True if a specified class is a subclass of a specified object
iter(): Returns an iterator object
len(): Returns the length of an object
list():Returns a list
locals():Returns an updated dictionary of the current local symbol table
map(): Returns the specified iterator with the specified function applied to each item
max(): Returns the largest item in an iterable
min(): Returns the smallest item in an iterable
next(): Returns the next item in an iterable
object(): Returns a new object
oct():Converts a number into an octal
open(): Opens a file and returns a file object
ord():Convert an integer representing the Unicode of the specified character
pow(): Returns the value of x to the power of y
print():Prints to the standard output device
property(): Gets, sets, deletes a property
range(): Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
round(): Rounds a numbers
set(): Returns a new set object
setattr():Sets an attribute (property/method) of an object
slice(): Returns a slice object
sorted(): Returns a sorted list
str(): Returns a string object
sum(): Sums the items of an iterator
tuple():Returns a tuple
type(): Returns the type of an object
vars(): Returns the __dict__ property of an object
zip(): Returns an iterator, from two or more iterators

iii. Modules :

As the programs become more lengthy and complex, there arises a need for the tasks to be split into smaller segments called modules. A module is a file containing  functions and variable defined in separate files. A module is simply a file that contains Python code or a series of instructions . When we break a program into modules , each module should contain functions that performs related tasks . There are some commonly used modules in Python that are used for certain predefined tasks and they are called libraries.

Modules also make it easier to reuse the same code in more than one program. If we have written a ste of functions that is needed in several different programs , we can place those functions that is needed in several different programs, we can place those functions in a module. Then we can import the module in each program that needs to call one of the functions . Once we import a module we can refer to any of its functions or variable in our program.

A module in Python is a file that contains a collection of related functions.

Python function definition can, usefully, be stored in one or more separate files
for easier maintenance and to allow them to beused in several programs without
copying the definitions into each one. Each file storing function definitions is
called a “module” and the module name is the file name with “.py” extension.


Example:
Functions stored in the module are made available to a program using the Python
import keyword followed by the module name. Although not essential, it is
customary to put any import statements at the beginning of the program.
Imported functions can be called using their name dot -suffixed after the module
name. For example, a “f1()” function from an imported module named
userdefined” can be called with userdefined.f1() .
Design a new Python module called userdefined by defining all functions as
illustrated below. Save the file as userdefined.py and run the file.

Start a new script with name importexample.py (/ipynb). Next call each function
with and without arguments as per the requirements. Run the program and get
the output as illustrated below:

Importing Modules in a python Program

Python language provides two important methods to import modules in a program which are as follows :

  • Import statement : To import entire module
  • From :To import all functions or selected ones
  • Import : To use module in a program , we import them using the import statement.

Syntax : import modulename1 [ modulname2,——]

It is the simplest and the most common way to use modules in our code.

Example for importing math

Output

Random module (Generating random numbers)

The various functions associated with the module are explained as follows :

randrange( ) :

This method generates an integer between its lower and upper argument . By default the lower argument is 0 and upper argument is 1. The following line of code generates random numbers from 0 to 29 . In this instance it is 15.

random() :

This function generates a random number from 0 to 1 such as 0.564388 . This function can be used to generate random floating point values. It takes no parameters and returns values uniformly distributed between 0 and 1 (including 0 , but excluding 1).

random.randint()

random.uniform()

random.choice()

random.shuffle()

Importing the sys and keyword modules :

Python includes “sys” and “keyword” modules that are useful for interrogating
the Python system itself. The keyword module contains a list of all Python
keywords in its kwlist attribute and provides as iskeyword () method if you want
to rest a word.

Python Module sys.path

To display the list of All Python Keywords

Sample Programs

Example1: A Short Program , Guess the Number

Project: Write a function named collatz() that has one parameter named number. If
number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps
calling collatz() on that number until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner
or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t
sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)
Remember to convert the return value from input() to an integer with
the int() function; otherwise, it will be a string value.
Hint: An integer number is even if number % 2 == 0, and it’s odd if
number % 2 == 1.

Questions for Practice:

  1. What are the advantages of using functions in a program?
  2. When the code in the function does executes during definition or calling.
  3. Discuss How to create a function with example.
  4. Explain the following with example
    1. Functions
    1. Function Call
    1. Built in Function
    1. Type Conversion Functions
    1. Random Numbers
    1. Math Functions
    1.  Adding new Functions
    1.  Defining and using the new functions
    1.  Flow of execution
    1. Parameter and Arguments
    1. Fruitful and void Functions
    1.  Advantages of Functions
  5. Differentiate between argument and parameter.
  6. What is the difference between a function and a function call?
  7. How many global scopes and local scopes are there in Python program?
  8. What happens to variables in a local scope when the function call returns?
  9. What is a return value? Can a return value be part of an expression?
  10. What is the return value of the function which does not have return statement?
  11. How can you force a variable in a function to refer to the global variable?
  12. What is the data type of None?
  13. What does the import allname statement do?
  14. If you had a function named  radio() in a module named car who would you call it after importing car.
  15. How can you prevent a program from crashing when it gets an error?
  16. What goes in the try clause? What goes in the except clause?
  17. Illustrate the flow of execution of a python function with an example program to convert given Celsius to Fahrenheit temperature.
  18. Explain the function arguments in python.
  19. Explain call by value and call by reference in python
  20. Briefly explain about function prototypes
  21. Define the scope and lifetime of a variable in python
  22. Point out the uses of default arguments in python
  23. Generalize the uses of python module.
  24. Demonstrate how a function calls another function. Justify your Apply answer
  25. List the syntax for function call with and without arguments.
  26. Define recursive function
  27. Define the syntax for passing arguments.
  28. What are the two parts of function definition give the syntax
  29. Briefly discuss in detail about function prototyping in python. With suitable example program
  30. Analyze the difference between local and global variables.
  31. Explain with an example program to circulate the values of n variables
  32. Describe in detail about lambda functions or anonymous function.
  33. Describe in detail about the rules to be followed while using Lambda function.
  34. Explain with an example program to return the average of its argument
  35. Explain the various features of functions in python.
  36. Describe the syntax and rules involved in the return statement in python.
  37. Write a program to demonstrate the flow of control after the return statement in python.
  38. Formulate with an example program to pass the list arguments to a function.
  39. Write a program to perform selection sort from a list of numbers using python.
  40. Give the use of return () statement with a suitable example.
  41. What are the advantages and disadvantages of recursion function? A
  42. Explain the types of function arguments in python
  43. Explain recursive function. How do recursive function works? Explain with a help of a program
  44. Illustrate the concept of local and global variables.
  45. A polygon can be represented by a list of (x, y) pairs where each pair is a tuple: [ (x1, y1), (x2, y2), (x3, y3) , … (xn, yn)]. Write a  Recursive function to compute the area of a polygon. This can be accomplished by “cutting off” a triangle, using the fact that a triangle with corners (x1, y1), (x2, y2), (x3, y3) has area (x1y1 + x2y2 + x3y2 – y1x2 –y2x3 – y3x1) / 2.
  46. What is a lambda function?
  47. How Do We Write A Function In Python?
  48. What Is “Call By Value” In Python?
  49. What Is “Call By Reference” In Python?
  50. Is It Mandatory For A Python Function To Return A Value? Comment?
  51. What Does The *Args Do In Python?
  52. What Does The **Kwargs Do In Python?
  53. Does Python Have A Main() Method?
  54. What Is The Purpose Of “End” In Python?
  55. What Does The Ord() Function Do In Python?
  56. What are split(), sub(), and subn() methods in Python?
  57. Describe the syntax for the following functions and explain with an example:  a) abs()   b) max()    c) divmod()   d) pow()   e) len() 

Programs for Practice:

  1. Write a program to generate Fibonacci series upto the given limit FIBONACCI(n) function.
  2. Write a single user defined function named ‘Solve’ that returns the Remainder and Quotient separately on the Console.
  3. Write a program to find i) The largest of three numbers and ii) check whether the given year is leap year or not with functions.
  4. Find the area and perimeter of a circle using functions. Prompt the user for input
  5. Write a Python program using functions to find the value of nPr and nCr without using inbuilt factorial() function. 
  6. Write a program to find the product of two matrices.
  7. A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided by 1, 2, 3, and 6.
  8. Write a function named isPrime, which takes an integer as an argument and returns True if the argument is a prime number, and False otherwise. Define a function main() and call isPrime() function in main() to display a list of the prime numbers from 100 to 500.
  9. Write a program that lets the user perform arithmetic operations on two numbers. Your program must be menu driven, allowing the user to select the operation (+, -, *, or /) and input the numbers. Furthermore, your program must consist of following functions:
    • Function showChoice: This function shows the options to the user and explains how to enter data.
    •  Function add: This function accepts two number as arguments and returns sum.
    • Function subtract: This function accepts two number as arguments and returns their difference.
    • Function mulitiply: This function accepts two number as arguments and returns product.
    • Function divide: This function accepts two number as arguments and returns quotient. Define a function main() and call functions in main().
  10. Write a Python function for the following :
    • To find the Max of three numbers.
    • To sum all the numbers in a listTo multiply all the numbers in a list.
    • To reverse a stringTo calculate the factorial of a number (a non-negative integer).
    • The function accepts the number as an argument
    • To check whether a number is in a given range
    • That accepts a string and calculate the number of upper case letters and lower case letters.
    • That takes a list and returns a new list with unique elements of the first list.
    • That takes a number as a parameter and check the number is prime or not.
    • To print the even numbers from a given list
    • To check whether a number is perfect or not.
    • That checks whether a passed string is palindrome or not.
    • That prints out the first n rows of Pascal’s triangle. 
  11. Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).
  12. Write a Python program to make a chain of function decorators (bold, italic, underline etc.) in Python.
  13. Write a Python program to execute a string containing Python code
  14. Write a Python program to access a function inside a function
  15. Write a Python program to detect the number of local variables declared in a function.
  16.  Write a function calculation() such that it can accept two variables and calculate the addition and subtraction of it. And also it must return both addition and subtraction in a single return call
  17. Create a function showEmployee() in such a way that it should accept employee name, and it’s salary and display both, and if the salary is missing in function call it should show it as 9000
  18. Create an inner function to calculate the addition in the following way
    • Create an outer function that will accept two parameters a and b
    • Create an inner function inside an outer function that will calculate the addition of a and b
    • At last, an outer function will add 5 into addition and return it
  19. Write a recursive function to calculate the sum of numbers from 0 to 10
  20. Write a function to calculate area and perimeter of a rectangle.
  21. Write a function to calculate area and circumference of a circle.
  22. Write a function to calculate power of a number raised to other. E.g.- ab.
  23. Write a function to tell user if he/she is able to vote or not.( Consider minimum age of voting to be 18. )
  24. Print multiplication table of 12 using recursion.
  25. Write a function to calculate power of a number raised to other ( ab ) using recursion.
  26. Write a function “perfect()” that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
  27. Write a function to check if a number is even or not.
  28. Write a function to check if a number is prime or not.
  29. Write a function to find factorial of a number but also store the factorials calculated in a dictionary as done in the Fibonacci series example.
  30. Write a function to calculate area and perimeter of a rectangle.
  31. What is the output of the following code segments ?
a) 
def foo(u, v, w=3):
        return u * v * w
 
def bar(x):
    y = 4
    return foo(x, y)

print(foo(4,5,6))
print(bar(10))


b) 

def change(t1,t2):
    t1 = [100,200,300]
    t2[0]= 8
	
list1 = [10,20,30]
list2 = [1,2,3]
change(list1, list2)
print(list1)
print(list2)


c) 

def dot(a, b):
    total = 0
    for i in range(len(a)):
        total += a[i] * b[i]
    print(total)

x = [10,20,30]
y = [1,2,3,4]
dot(x,y)


d) 

def buz(arr, n):
    for i in range(n-1):
        if arr[i]>arr[i+1]:
            arr[i], arr[i+1] = arr[i+1], arr[i]
    print(arr)

def bar(arr,n):
    for i in range(n-1):
        buz(arr,n-i)
    
t = [19,7,4,1]
bar(t,len(t))


e)

def change(num1 ,num2=50):		
    num1 = num1 + num2		
    num2 = num1 - num2		
    print(num1, '#', num2)				

n1 = 150			
n2 = 100			
change(n1,n2)		
change(n2)
change(num2=n1,num1=n2)

#########################################################################