Python Fundamentals – Functions

Python Fundamentals – Functions

WHAT IS A FUNCTION?

A function can be equated to a “blackbox” to which one or more input values are passed, some processing is done, and output value is then returned automatically.
Python function is a grouping of program statements put into a single unit to carry out tasks at a given level. Each Python function can be activated through the execution of a function call. Functions in Python are used because of the following reasons:

  • The use of functions enables us to write Python program in logically indepen­dent sections in the same way as we develop the solution algorithm.
  • Functions may be executed more than once in a program. Also if we have written and tested a function subpro­gram, we may use it in other programs or other functions.
  • The complexity of a program can be divided into simple subtasks and function subprograms can be written for every subtasks.
  • The subprograms are easier to write, understand and debug.
  • A function can be shared by other pro­grams by compiling it separately and finally loading them together.     .
  • In Python, a function can call the same function again. It is called recursiveness.
    Many calculations can be done easily using recursive process, such as calculation of factorial of a number.
  • Built-in function, are the function(s) that are build into Python and can be accessed by a programmer. For example len(), type(), int(), raw_input(), etc.

TYPES OF FUNCTIONS

Functions are of three types. These are:

  • Module
  • Built-in Functions
  • User Defined Functions

User defined functions will be discussed in detail in the next Chapter. In this Chapter, we shall understand different built-in functions and some functions defined in Python modules, i.e., math module and random module in detail.

Module
A module is a file that contains a collection of related functions and other definitions. You can make a module available to another program by importing it.                                                  .
Modules are the key to Python’s portability and power. Modules are extensions that can be imported into Python to extend its capabilities. Python itself is made up of modules. For example, Python has a math module that includes a number of specialized mathe­matical tools, and it also defines some names, including pi. Here’s how you import

Here’s how you access the name pi that it defines:

Note that you can import modules with the import command. To use a module, you can import it. Usually import statements occur at the beginning of the Python module. Importing modules is a fairly simple operation, but it requires a little explanation. Con­sider the following examples:

  • import math
  • import os, sys
  • from math import sqrt
  • import os as operatingSystem .

These examples highlight some variations in how you can import modules:

  • This first example is the simplest and easiest to understand. It is merely the key­word import followed by the module name (in this case, math). The standard way to import a module, say math, is to write:
and then access individual functions in the module with the module name and prefix as given below:
  • Multiple modules can be imported with the same import command, with the modules separated by a comma.
  • You can import specific names only within a module, without importing the whole module, by using the f rom <module> import <name> This can be useful for performance reasons if you only need one function from a large module. Now we can work with sqrt directly, without the math prefix. More than one function can be imported:
Sometimes one just writes
to import all functions in the math module. This includes sin, cos, tan, asin, acos, atan, sinh, cosh, tarrh, exp, log (base e), loglO (base 10), sqrt, as well as the famous numbers e and pi. Importing all functions from a module, using the asterisk (*) syntax, is convenient, but this may result in a lot of extra names in the program that are not used.
It is in general recommended not to import more functions than those that are really used in the program

  • If a module has a name that is difficult, to work with or remember, and ySu want to use a name to represent it that is meaningful to you, simply use the as keyword and import <module> as <identifier> .

Built-in Functions
Built-in functions are the functions that are built into Python and can Jse accessed by programmer any time without importing ciny module (file) such functions are input(), raw_input(), int(), float(), type() etc.
The int(), long(), float(), and complex() built-in functions are used to convert from any numeric type to another.
The following are some examples using the numeric type conversion built-ins:

Built-in function is accessed simply by writing the function name, followed by an optional list of arguments that represent information being passed to the function.
The arguments passed to a function must be enclosed in parentheses and separated by commas. The arguments can be constants, variable names, or more complex expres­sions. The parentheses must be present, even if there are no arguments.

User Defined Functions
Apart from the library functions that are inbuilt in Python, users can also define func­tions to do a task relevant to their programs. Such functions are called user defined functions. These functions should be codified by the user, so that any call to the function can refer to it.

WORKING WITH math MODULE

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions. Before we can use the module, we have to import it.

This statement creates a module object named math. If you print the module object, you get some information about it:

The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation. Following sections lists some useful math function to be used as math.<function-name> in your program.

fabs()
The fabs() function returns the absolute value of the x. The general form is:

Example 1

Figure 13.1 Use of fab() function


ceil()

The method ceil() returns the smallest whole number greater than or equal to x. The general form is:

Example 2

Figure 13.2 Use of ceil() function

floor( )
The floor() method returns the largest whole number less than or equal to x.

Example 3

Figure 13.3 Use of floor( ) function

log()
The log() function returns the natural logarithm of x. If x is negative, a domain error occurs. If x is zero, a range error may occur.

With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).
Note if you write negative number, it will display error as follows:

Example 4

Figure 13.4 Use of log( ) function

log 10( )
The log10() function returns the base-10 logarithm of num. If num is negative, a domain error occurs. If num is zero, a range error may occur. The log10() function use is used as follows:

Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
Example 5

Figure 13.5 Use of log10() function

exp( )
The exp( ) function returns the exponential number E raised to the power of a.

Example 6

Figure 13.6 Use of exp() function

sqrt()
The sqrt() function returns the non-negative square root of x. If x is negative, a domain error occurs.

Example 7

Figure 13.7 Use of sqrtQ function

Example 8
The program shown in Figure 13.8 uses the sqrt (square root) to compute the roots of a quadratic equation of the form:
ax2 + bx + c = 0

Figure 13.8 Using sqrt()

sin()
It calculates the sine of the angle whose value is entered in radians.

Example 9

Figure 13.9 Use of sin() function

cos()
It calculates the cosine of the angle whose value is entered in radians.

Example 10

Figure 13.10 Use of cos() function

tan()
It calculates the tangent of the angle whose value is entered in radians.

Example 11

Figure 13.11 Use of tan() function

degrees()
The degrees() converts angle x from radians to degrees.

Example 12

Figure 13.12 Use of degree() function

radians()
The radians() converts angle x from degrees to radians.

Example 13

Figure 13.13 Use of radians() function

WORKING WITH random MODULE

Modules are files that contain code meant to be used in other programs. These modules usually group together a collection of programming related to one another. The random module contains function related to generating random numbers and producing ran­dom results. Random numbers have many applications in science and computer pro­gramming, especially when there are significant uncertainties in a phenomenon of interest. The first line of code in the program introduces the import statement. The statement allows you to import or load modules. In case of random module:

random()
The random module contains functions that return random numbers, which can be use­ful for simulations or any program that generates random output. Python has a module random for generating random numbers. The numbers generated by random.random() tend to be equally distributed between 0 and 1. The random function can be used to generate pseudorandom floating point values. It requires no parameters and returns values uniformly distributed between 0 and 1 (including 0, but excluding 1). The fol­lowing example shows the usage of random() function:

Example 14

Figure 13.14 Use of random() function

randint()
If we wanted a random integer, we can use the randint function. Randint accepts two parameters: a lowest and a highest number and returns an integer between lowest and highest (including both).
This function is not accessible directly so we need to import random module and then we need to call this function using random static object. Generate integers between 1,5. The first value should be less than the second. This will output either 1, 2,3, 4 or 5.

Example 15

Figure 13,15 Use of randint() function

uniform()
The function random.uniform, when supplied with two numerical parameters a and b, returns a random (uniformly distributed) real number.

Example 16

Figure 13.16 Use of uniform() function

randrange()
randrange([start], stop, [step]) Returns a random number from range(start, stop, step). The function random.randrange is the standard function for generating a random inte­ger in the range you would get by calling range with the same arguments. For example, to get a random number in the range from 1 to 10 (inclusive), you would use randrange(l,ll) (or, alternatively, randrange(10)+1), and if you want a random odd positive integer lower than 20, you would use randrange(1,20,2).

Example 17

Figure 13.17 Use of randrange() function

Example 18
Let’s ask the user how many dice to throw, and how many sides each one should have. The dice-throwing mechanism is implemented with randrange and a for loop.

Figure 13.18 Use of randrange() function

WORKING WITH BUILT-IN FUNCTIONS

Built-in functions are the functions that are built into Python and can be accessed by programmer any time without importing any module (file). So you use built-in func­tions of Python directly as:

abs()
abs() returns the absolute value of the given argument. Here are some examples of using the abs() built-in function:

Example 19

Figure 13.19 Use of abs() function

max()
Python built-in function max() returns the largest of its parameters. Here is the simplest version of our program.

Example 20

Figure 13.20 Use of max() function

min()
Python built-in function min() returns the smallest of its parameters. Here is the sim­plest version of our program.

Example 21

Figure 13.21 Use of min() function

cmp()
The cmp() built-in function compares two objects, say, objl and obj2, and returns a neg­ative number (integer) if objl is less than obj2, a positive number if objl is greater than obj2, and zero if objl is equal to obj2.

Example 22

Figure 13.22 Use of cmp() function

divmod()
The divmod() built-in function combines division and modulus operations into a single function call that returns the pair (quotient, remainder) as a tuple. The values returned are the same as those given for the standalone division and modulus operators for inte­ger types. For floats, the quotient returned is math.floor( numl/num2 ) and for complex numbers, the quotient is math.floor(( num1/num2 ).real).

Example 23

Figure 13.23 Use of divmod() function

Example 24

Figure 13.24 Use of divmod() function

pow()
Both pow() and the double star (** ) operator perform exponentiation. ** is an operator and pow() is a built-in function. The pow(x,y) function returns the value of x raised to the power of y, i.e.,xy.

Example 25

Figure 13.25 Use of pow() function

len()
The function len() returns the number of elements a sequence contains.

Example 26

Figure 13.26 Use of len() function

range()
The range() function generates lists containing arithmetic progressions.

Example 26

Example 27

Figure 13.27 Use of range() function

round()
The round() built-in function has a syntax of round (flt,ndig=0). It normally rounds a floating point number to the nearest integral number and returns that result (still) as a float. When the optional third ndig option is given, roundQ will round the argument to the specific number of decimal places.

Example 28

Figure 13.28 Use of round() function

COMPOSITION

Using an expression as part of a larger expression, or a statement as part of a larger statement is called composition. Composition is an art of combining simple function(s) to build more complicated ones, i.e., result of one function is used as the input to another. For example,
Suppose we have two functions fund & func2, such that one function is passed as argument to next and result of the last one is the final result.
a= func2(x)
b= func1 (a)
then call to the two functions can be combined as composition as follows: b= func1(func2 (x))

SOLVED EXERCISE

Question 1.
What is the purpose of a header file in a Python program?

Answer:
A header file provides a centralized location for the declaration of all extern vari¬ables, function prototypes, etc. Files that must use or define a variable or a function, include header file(s). By using header files, two main safeguards are provided.

Question 2.
What is function?

Answer:
A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.

Question 3.
What are the advantages of using functions.

Answer:
Functions let you write code only once.
Functions hide unnecessary complexity from the user.
Functions make your code easier to understand.
Functions help you organize your program logically.

Question 4.
What is function definition?

Answer:
A statement that creates a new function, specifying its name, parameters, and the , statements it executes is called function definition.

Question 5.
Write a short note on built-in function.

Answer:
Built-in functions are the functions that are built into Python and can be accessed by programmer any time without importing any module (file) such functions are input(), raw_input(), int(), float(), type() etc.

Question 6.
How is built-in function accessed?

Answer:
Built-in function is accessed simply by writing the function name, followed by an optional list of arguments that represent information being passed to the function.

Question 7.
How will you import all functions in the math module?

Answer:
from math import *

Question 8.
What is difference between ceil() and floor() functions?

Answer:
The function ceil() returns the smallest whole number greater than or equal to x. The floor() function returns the largest whole number less than or equal to x.

Question 9.
What is Python module?

Answer:
A module is a file that contains a collection of related functions and other definitions. You can make a module available to another program by importing it.

Question 10.
How will you import specific names only within a module?

Answer:
You can import specific names only within a module, without importing the whole module, by using the from import statement.

Question 11.
Write short note on user defined function.

Answer:
Apart from the library functions that are in-built in Python, users can also define functions to do a task relevant to their programs. Such functions are called user- defined functions. These functions should be codified by the user, so that any call to the function can refer to it.

Question 12.
What is difference between pow() and **?

Answer:
Both pow() and the double star (** ) operator perform exponentiation. ** is an opera-tor and pow() is a built-in function.

Question 13.
How cmp() function compares objects?

Answer:
The cmp() built-in function compares two objects, say, obj1 and obj2, and returns a negative number (integer) if obj1 is less than obj2, a positive number if obj1 is greater than obj2, and zero if obj1 is equal to obj2.

Question 14.
Differentiate between max() and min() functions?

Answer:
Python built-in function max() returns the largest of its parameters. Python built-in function min() returns the smallest of its parameters.

Question 15.
Write a short note on random module.

Answer:
The random module contain function related to generating random numbers and producing random results. Random numbers have many applications in science and computer programming, especially when there are significant uncertainties in a phenomenon of interest.

Question 16.
Write a short note on randint().

Answer:
If we wanted a random integer, we can use the randint() function. Randint accepts two parameters: a lowest and a highest number, and returns an integer between lowest and highest (including both).

Question 17.
Write a program to calculate area of the parallelogram, area of the square, area of the circle and the volume of the cone. Import pi constant, from math module.

Answer:

Question 18. Multiple choice questions

Question 1.
The ceil() returns whole number greater than or equal to x.
(a) Smallest
(b) Largest
(c) Any
(d) None of the above

Answer:
(a)

Question 2.
Named block of statements within a program is known as:
(a) Module
(b) Function
(c) Namespace
(d) None of these

Answer:
(b)

Question 3.
Built-in function:
(a) len()
(b) type()
(c) raw_input()
(d) All of the above

Answer:
(d)

Question 4.
A module
(a) Is independent grouping of code and data
(b) Can be re-used in other programs
(c) Can depend on other modules
(d) All of the above

Answer:
(d)

Question 5.
Standard library module:
(a) math module
(b) random module
(c) Both (a) and (b)
(d) None of these

Answer:
(c)

About the author

James Palmer

Leave a Comment