﻿ ﻿FUNCTIONS - Python Programming Made Easy (2016)

# Python Programming Made Easy (2016)

### Chapter 3: FUNCTIONS

Functions are the most important building blocks in any programming language, especially Python. A function is a block of statements that perform a computation. The lines of code inside a function are executed sequentially. Fig 3.1: Functions

Built-in functions

Built-in functions are the functions that are built into Python and can be accessed by a programmer. Table 3.1: Python built-in functions

Some important functions are explained below

 S.No Function Description Example 1 abs(x) Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. abs(-4.0) 4.0 2 cmp(x,y) Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. cmp(6,7) -1 3 divmod(a, b) Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. divmod(8,8) (2,2) 4 len(s) Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary). len(“Python”) 6 5 max(arg1, arg2, *args[, key]) Return the largest item in an iterable or the largest of two or more arguments. The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)). max( 8, 56, 34) 56 max( "India","China","Japan") 'Japan' 6 min(arg1, arg2, *args[, key]) Return the smallest item in an iterable or the smallest of two or more arguments. The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)). min(8,56,34) 8 min('India','China','Japan') 'China' 7 range(stop) range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. step must not be zero (or else ValueError is raised). for i in range(0,20,2): print i, 0 2 4 6 8 10 12 14 16 18 8 round(number[, ndigits]) Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero. round(0.5) 1.0 round(-2.2) -2.0 round(3.14127,2) 3.14 9 type(object) type(name, bases, dict) With one argument, return the type of an object. The return value is a type object.The isinstance() built-in function is recommended for testing the type of an object. str ="Python" type(str) a = 5 type(a) 10 tuple([iterable]) Return a tuple whose items are the same and in the same order as iterable‘s items. tuple([1,2,3,4,5]) (1, 2, 3, 4, 5) 11 id(object) Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. a = 5 id(a) 30991416L

Table 3.2: Important built-in functions

* Data type conversion functions have been already discussed in chapter 2

Modules

A module is a file containing Python definitions and statements. We need to import modules to use any of its functions or variables in our code.

Syntax:

import modulename1 [,modulename2,…]

 Example: import math value=math.sqrt(25)

Syntax:

From modulename import functionname [,functionname]

 Example: from math import sqrt value=sqrt(25)

Note: It’s a good programming practice to put all the import statements at the beginning of the Python file.

Some important modules are math, random, string, time, date.

Math module

Some important functions in math module are listed in the table below

 Function Description Example ceil(x) Return the smallest integer value greater than or equal to x. import math math.ceil(40.3) 41.0 floor(x) Return the largest integer value less than or equal to x. math.floor(39.9) 39.0 exp(x) Returns ex math.exp(1) 2.718281828459045 pow(x, y) Returns xy math.pow(8,3) 512.0 sqrt(x) Return the square root of x. math.sqrt(25) 5.0 hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y). math.hypot(6,6) 8.48528137423857 degrees(x) Converts angle x from radians to degrees. math.degrees(3.14) 179.9087476710785 radians(x) Converts angle x from degrees to radians. math.radians(180) 3.141592653589793 cos(x) Return the cosine of x. math.cos(0) 1.0 sin(x) Return the sine of x. math.sin(0) 0.0 tan(x) Return the tangent of x. math.tan(0) 0.0 pi The mathematical constant pi. math.pi 3.141592653589793 e The mathematical constant e math.e 2.718281828459045

Table 3.3: Math module

Random module

Some important functions in random module are listed in the table below

 Function Description Example random.randrange(stop) random.randrange(start, stop[, step]) Return a randomly selected element from range (start, stop, and step). print random.randrange(2,10) 8 print random.randrange(2,10) 4 random.randint(a, b) Return a random integer N such that a <= N <= b. print random.randint(8,20) 19 random.seed([x]) Initialize the basic random number generator. Optional argument x can be any hashable object. If x is omitted or None, current system time is used; random.seed(5) print random.randint(0,10) 6 print random.randint(0,10) 8 random.choice(seq) Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError. print random.choice("Python") o

Table 3.4: random module

String module is discussed in Chapter 5

User –defined functions

Python provides many built in functions. But we can also create our own functions. These functions are called user-defined functions. There are a few rules for defining our own functions.

1. Function blocks begin with the keyword “def” followed by the function name and parantheses.

2. The first statement of a function can be an optional statement – docstring. It is the documentation string of the function which contains essential information about the function such as

à purpose of a function

àtypes of parameters

à return values

3. Any input parameters should be placed within these parameters.

4. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

5. By default, parameters have a positional behaviour, and we need to inform them in the same order as they were defined.

 Example 3.1: Function to add 2 numbers def add(a,b): ''' This functions adds 2 numbers''' c = a+b return c

Parameters and Arguments

Parameters are the values provided in the parenthesis in the function header when we define the function. Arguments are the values provided in function call/ invoke statement. Fig 3.2: Function arguments/parameters Fig 3.3: Types of parameters

Required arguments are the arguments passed to a function in correct positional order. Some functions require the arguments to be provided for all the parameters and order of arguments should be the same as in the definition.

Default arguments assume a default value if a value is not provided in the function call for that argument. A parameter having a default value in function header becomes optional in function call. Function call may or may not have value for it. They are used

è To add new parameters to the existing function

è To combine similar functions

è To provide greater flexibility to programmers

Keyword arguments allows us to skip arguments or place them out of order because the interpreter is able to use the keywords provided to match the values with parameters. The calling function identifies the arguments by the parameter name. This is a unique feature of Python where we can write any argument in any order provided we name the arguments. We can pass a dictionary as an argument.

The code snippet below explains it.

 def func(a='aa', b='bb', c='cc’, **keyargs): ... print a, b, c ... >>> func() aa bb cc >> func(**{'a' : 'x', 'b':'y', 'c':'z'}) x y z >>>

Here, the order of parameter does not matter.

1. We need not remember the order of the arguments

2. We can specify values to only those parameters we want to

Variable-length arguments are not named in the function definition.

 Example 3.2: Variable-length arguments def add(*numbers): sum =0 for number in numbers: sum = sum + number print sum add(1,2,3,4,5) add(2,4,6)

This allows us to add any number of values.

Anonymous functions

Functions using the lamda keyword without using “def” keyword are called anonymous functions.

 Example 3.3: Anonymous functions sum = lamda a,b:a+b print sum(5,10)

Lamda forms can take any number of arguments but return just one value in the form of an expression.

Scope of variables

The scope of a variable determines the portion of the program where we can access a particular variable.

Global scope: A variable with global scope can be used anywhere in the program and it is declared outside all functions/blocks.

Local scope: When a variable is created inside the function/block, the variable becomes local to it.

 Example 3.4: Scope x=10 # global variable def printx(): y=5 # local variable print x+y print x printx() print y # NameError: name 'y' is not defined

Composition

The act of joining 2 or more functions together is called composition.

 Example 3.5 print math.degrees(math.pi) 180.0

Solved Questions

1. Define a function getLargest(x,y) to take in 2 numbers and return the larger of them.

Ans:

def getLargest(x,y):

if x>y:

return x

else:

return y

2. Write a python program to simulate a basic calculator using functions for add, subtract, multiply and divide.

Ans:

return (x+y)

def sub(x,y):

return (x-y)

def mul(x,y):

return (x*y)

def div(x,y):

return (x/y)

#calculator program

loop = 1

#this variable holds the user's choice in the menu:

choice = 0

while loop == 1:

print " Four function calculator - choose your option:"

print "2) Subtraction",

print "3) Multiplication",

print "4) Division",

print "5) Quit"

choice = input("Choose your option: ")

if choice == 1:

add1 = input(" First number: ")

add2 = input(" Second Number: ")

elif choice == 2:

sub1 = input("First number: ")

sub2 = input("Second Number: ")

print sub1, "-", sub2, "=", sub(sub,sub2)

elif choice == 3:

mul1 = input("First number: ")

mul2 = input("Second Number: ")

print mul1, "*", mul2, "=", mul(mul1,mul2)

elif choice == 4:

div1 = input("First number: ")

div2 = input("Second Number: ")

print div1, "/", div2, "=", div(div1,div2)

elif choice == 5:

loop = 0

print "Done !!"

Practice problems

1. Define a function ‘SubtractNumber(x,y)’ which takes in two numbers and returns the difference of the two.

2. Write a function in python to calculate the power of a given number. If user doesn’t specify the exponent it should return the square of the number.

﻿