Functions in Python
Python allows dividing large programs into smaller modules called functions.
Functions help manage complexity and save time by avoiding repetitive code.
Sub-programs can be further divided into smaller sub-programs as needed.
Functions facilitate problem-solving by dividing problems into sub-problems, solving them individually, and integrating the solutions.
This approach is known as the stepwise refinement method or divide and conquer approach.
2.2 FUNCTIONS
A function is a group of statements performing a specific task within a program.
Large programs can be written as several small functions.
Functions consist of a sequence of instructions executed sequentially by the Python interpreter.
A function is a named group of statements that can be invoked (called) from another part of the program.
Example: School Management Software uses functions for tasks like registering students, fee collection, etc.
Analogy: Dishwasher as a Function
A dishwasher works similarly to a function: dirty dishes go in, and clean dishes come out.
The dishwasher performs tasks like adding detergent and water, washing, and drying.
Input: Dirty Dishes
Output: Clean Dishes
Function Arguments are INPUT.
Return Value is OUTPUT.
Python Functions
Functions take data as input, perform a defined task, and provide output.
Python's script mode allows retaining work for future usage.
To work in script mode, write a function and save it in a .py file.
A Python function is written once and can be used/called multiple times.
Functions are essential building blocks in Python, working on the divide and conquer approach.
Advantages of Functions:
Easier program handling: Small parts of the program are dealt with at a time.
Reduced lines of code: Common code is written once and called from anywhere.
Easy updation: Changes are made in one location (the function itself).
Easier to use: No need to remember the order of arguments.
Flexibility: Specify values only for the parameters you want
Improved readability: Help in breaking down complex problems into smaller, manageable parts
2.3 Types of Functions
Functions are categorized into three types:
Built-in Functions
Modules
User-defined Functions
2.3.1 Built-in Functions
These are predefined functions in Python's standard library.
They provide efficiency and structure and are always available without importing modules.
Type conversion functions
Python converts values from one type to another.
int(): Converts a value to an integer.
If no argument is passed, int() returns 0.
Converts floating-point values to integers by chopping off the fraction part.
An error occurs if a string value is given as an argument (e.g., int("Hello")
Example: int(334.56) outputs 334
str(): Converts its argument into a string.
Example: str(233) outputs '233'
float(): Converts integers and strings into floating-point numbers.
If no argument is passed, float() returns 0.0.
If the argument is a number, float() returns the same number as a float (e.g., float(26) returns 26.0).
If the argument is an expression, the expression is evaluated, and float() returns its value (e.g., float(33+25) returns 58.0).
If the argument is a string containing a floating-point number in correct format, float() returns the float value represented by this string (e.g., float('3.14159')
returns 3.14159).An error results if the string argument contains any character other than a leading sign and number (e.g. float('40.63+')).
input() function
Accepts input from the user as a string, without evaluating its value.
Continues to read input until a new line is encountered.
Example:
name = input('Enter a name: ')
print('Welcome', name + 'Pleasure to meet you')
eval() function
Evaluates the value of a string and returns the numeric result (int or float, as appropriate).
If the argument is not a string or cannot be evaluated as a number, eval() results in an error.
Example:
x = eval('45+10')
print (x)
min() and max() functions
Used to find the minimum and maximum value respectively.
The max() function takes two or more arguments and returns the largest one.
The min() function takes two or more arguments and returns the smallest one.
Example:
min (23, -109, 5, 2)
returns -109
abs() function
Returns the absolute value of a single number.
Takes an integer or float number as an argument, and always returns a positive value.
Example:
abs (-50)
50
type() function
Determines the type of a variable.
Returns the class of the argument.
The Boolean argument given to type() function should have T (capital letter) for True and F (capital letter) for False; otherwise, it will generate an error.
Example:
type (10)
len() function
Returns the length (the number of items) of an object.
Argument may be a sequence (string, tuple or list) or a mapping (dictionary).
Example:
x= [1,2,3,4]
len(x)
4
round() function
Rounds a given floating-point number to the specified number of digits and returns the result.
Syntax: round (n,p)
n can be an integer or a floating-point value.
p is an optional argument and must be an integer.
If p is not specified, n is rounded to 0 digits of the decimal, and the result is an integer.
If p is 0, n is rounded to 0 digits of the decimal, and the result is a float value.
If p is a positive integer, n is rounded to p digits by checking ({p+1})^{th} digit; if it is 5 or >5, then the {p}^{th} digit is increased by 1, and the result is a float.
If p is a negative integer, n is rounded up to p digits before the decimal by checking the {p}^{th} digit; if it is 5 or >5, then the (p-1)^{th} digit is increased by 1, all trailing p digits are converted to zero, and the result is a float.
*range() function
Used to define a series of numbers and is particularly useful in 'for loops'.
Generates a series of integers from 0 to n-1:
Example: range(5) -> 0, 1, 2, 3, 4
Define the starting and ending number by specifying the two arguments for beginning and ending numbers range (begin, end)
We can change the way increments the number by introducing a third argument, the 'step': range (begin, end, stop)
/
2.2.2 Modules
As programs grow, splitting tasks into modules becomes necessary.
A module is a file containing functions and variables defined in separate files.
It's a file that contains Python code.
Makes a program easier to understand, test, and maintain.
When breaking a program into modules, each module should contain functions that perform related tasks.
Modules also make it easier to reuse the same code in more than one program.
CTM: A module in Python is a file that contains a collection of related functions.
Importing Modules in a Python Program
Python provides import keyword to import modules in a program.
There are two methods to import modules:
*import statement: Imports the entire module.
To import one module, the syntax is: import
Example: import math
To import multiple modules in a program, the syntax is: import [, …..]
Example: import math, time, OS
from import statement: To import all functions or the selected in a program, the syntax is:
from import *
Example: from math import *
To import a particular function of the module, we can use:
from math import sqrt
To import multiple functions, we can use:
from math import sqrt, pow, pi
import statement is the simplest and the most common way to use modules in our code.
For example, import math
The definitions of the module will become part of the code in which the module was imported.
dot notation: To access/use any of the functions present in the imported module, specify the name of the module followed by the name of the function, separated by a dot (also known as a period).
Example:
import math
result = math.sqrt (64)
math module
Returns smallest integer greater than or equal x ceil(x)
Returns largest integer less than or equal x floor(x)
It returns the value of x^y: pow(x, y)
Op returns absolute value of the expression/number fabs()
Module to display square root of a number sq_root()
Returns the base-10 logarithm of x log10(x)
Returns the cosine of x in radians cos(x)
Returns the sine of x in radians sin(x)
Returns the tangent of x in radians tan(x)
Python help() library function is useful for knowing the purpose of a function and how it is used.
Module related to strings and their manipulation has been addressed separately string module
Random Module:
Invoking random module:
import random
This module requires an explicit library.
Functions include:
randrange()
This method generates an integer between its lower and upper argument range. By default, the lower argument is 0 and upper argument is 1.
If the upper bound is n then it will pick a number from 0 to n-1
Syntax:
python random.randrange (30)
random()
This function generates a random number from 0 to 1 such as 0.5643888123456754.
It can be used to generate random floating-point values. It takes no parameters returns values uniformly distributed between 0 and 1 (including 0, but excluding 1).
randint()
This function accepts two parameters, a and b, as the lowest and highest number; returns a number 'N' in the inclusive range(a, b); which signifies a<=N<=b, where the endpoints a, b are included in the range.
uniform()
This method returns a random floating-point number in between two numbers. The syntax is:
python random.uniform (x, y)x is lower limit and y is the upper limit of random float.The returned random floating point number is greater than or equal to x and less than y.
choice()
This method is used for making a random selection from a sequence like a list, tuple, or string The syntax is:
python random.choice (sequence)
shuffle()
This method is used to shuffle or swap the contents of a list (that is, generate a random permutation of a list in-place). The syntax is:
python shuffle (list)
User-Defined Functions:
A function is a set of statements that performs a specific task; a common structuring element that allows you to use a piece of code repeatedly in different parts of a program.
How to define and call a function in Python()
A user-defined Python function is created or defined by the def statement followed by the function name, parentheses () and colon (:) as shown in the given syntax:
python def function_name(comma_separated_list_of_parameters): """docstring""" statement(s)
A function definition consists of the following components.
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules as rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid Python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
User-Defined Functions (UDFs) in Python are called using only the function name.
Significance of Indentation (Space) in PythonPython follows a particular style of indentation to define the code. Since Python functions don't have any explicit beginning or end, like curly braces to indicate the start and stop for the function, they have to rely on this indentation. We now take a simple example with “print” command.
How Function Returns a Value
Usually, function definitions have the following basic structure:
python def function_name (arguments): return <value>Function returning multiple values
Unlike other high-level languages like C, C++, Java, wherein a function can return at most one value, a function in Python can return multiple values.
Learning Tip:
A function may or may not return a value. In nutshell, while creating functions, we can use two keywords:
def (mandatory)
return (optional)
2.4 Parameters and Arguments in Functions
Parameters are the variable(s) provided in the parentheses when we write function header. These variables contain values required by the function to work. These parameters are called formal parameters.
Arguments in Python can be one of these value types-literals or variables or expressions- but the parameters have to be some names, i.e., variables to hold incoming values; parameters cannot be literals or expressions.
The values used in function call are actual parameter and actual argument.
The variables used in function header are formal parameter and formal argument.
A few things to remember about parameter passing: In Python functions, if you are passing values of immutable types, i.e., numbers, strings, etc., to the called function, then the called function cannot alter their values. But in case parameters passed are mutable in nature, such as lists or dictionaries, then called function would be able to make changes to them.
Functions may be simple one-to-one mappings
They may contain multiple input and/or output variables as well as return multiple values.
Functions don't need to contain arguments at all.
If there is a function with many parameters and we want to specify only some of them in function call, then value for such parameters can be provided by using their name, instead of the position (order). This is called keyword arguments.
Four types of actual arguments are allowed in Python:
Positional arguments
Default arguments
Keyword arguments
Variable length arguments
Positional arguments: Positional arguments are arguments passed to a function in correct positional order.
Default arguments: A default argument is an argument that assumes a default value provided if a value is not provided in the function call for that argument. Sometimes we can provide default values for our positional arguments.
Keyword arguments: If there is a function with many parameters and we want to specify only some of them in function call, then value for such parameters can be provided by using their name instead of the position (order). These are called keyword arguments or named arguments.
CTM: Keyword arguments are the named arguments with assigned values being passed in the function call statement.
Advantages of writing functions with keyword arguments are:
Using the function with keyword arguments is easier as we do not need to remember the order of the arguments.
We can specify values of only those parameters which we want to, as other parameters have default argument values.
Variable length arguments: As the name suggests, in certain situations, we can pass variable number of arguments to a function. Such type of arguments are called variable length arguments/parameters.
Variable length arguments are declared with * (asterisk) symbol in Python as:
Passing Arrays/Lists to Functions*
Arrays in basic Python are actually lists that can contain mixed data types. However the num array module contains support for true arrays.
Passing Strings to a Function
String can be passed to a function as an argument. Since it is an immutable object in Python, it is used as pass by value. Thus, a function can access the value of a string but cannot modify it.
Passing Tuple to a Function
You can also pass a tuple as an argument to a function. Because of its immutable nature, a function can only access the value of a tuple but cannot modify it.
Passing Dictionary to a Function
Python also allows us to pass dictionary to a function. Since dictionaries are mutable in nature, function can alter the values of dictionary in place.
2.9 Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
Global (module)
Names assigned at the top level of a module, i.e., outside of any function, or directly in the interpreter
Names declared with global keyword in a function
Can be accessed inside or outside of the function
Local (function)
Names assigned inside a function definition or loop
Cannot be accessed outside the function
Changing a global name used in a function definition changes the function.
2.10 Using main() as a Function
There is no restriction to including a main() function in Python, but it can structure Python programs and can make programs easier for non-Python programmers to read.
2.11 Flow of Execution of Program Containing Function Call
Execution always begins at the first statement of the program. Statements are executed one at
a time, starting from the top to the bottom. Function definition does not alter the flow of execution of a program, as the statement inside the function is not executed until the function is called.
2.12 Recursion
Recursion is a function that invokes itself. Recursion is defined as defining anything in terms of itself. In other words, it is a method in which a function calls itself one or more times in its body.
Conditions for Implementing Recursion
There must be a terminating condition for the problem which we want to solve with recursion. This condition is called the base case for that problem.
Each time a new recursive call is made, a new memory space is allocated to each local variable used by the recursive routine. In other words, during each recursive call to recursive function, the local variable of the recursive function gets a different set of values but with the same name.
In each call, the power function passes the actual parameters to the version being called. The value of x is same for each power function call, but the value of n is decremented by 1 for each call until n becomes zero. When n becomes 0, the function power() starts returning a value X and this value of power() function is passed back to the previous version that made this call and this process of returning values will continue until the value of the power can be passed to
the original call. When we define a function recursively, then there must exist such condition that is responsible for its termination.
Recursion vs Iteration
When a loop is executed repeatedly, it uses the same memory locations for variables and repeats the same unit of code. On the other hand, recursion, instead of repeating the same unit of code and using the same memory locations for variables, allocates fresh memory space for each recursive call.