Python Functions_Unit3 1
Python Functions_Unit3 1
FUNCTIONS: Definition - Passing parameters to a Function - Built-in functions- Variable Number of Arguments
- Scope – Type conversion-Type coercion-Passing Functions to a Function - Mapping Functions in a Dictionary
– Lambda - Modules - Standard Modules – sys – math – time - dir - help Function.
Python -Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can alsocreate
your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define afunction
in Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( )).
Any input parameters or arguments should be placed within these parentheses. You can alsodefine
parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of thefunction
or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to thecaller. A
return statement with no arguments is the same as return None.
Syntax
By default, parameters have a positional behavior and you need to inform them in the same orderthat they
were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
1/9
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and
structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or
directly from the Python prompt. Following is the example to call printme() function −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
2/9
"This changes a passed list into this function"mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
Here, we are maintaining reference of the passed object and appending values in the same object.So, this
would produce the following result −
There is one more example where argument is being passed by reference and the reference isbeing
overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
The parameter mylist is local to the function changeme. Changing mylist within the function does notaffect
mylist. The function accomplishes nothing and finally this would produce the following result −
3/9
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are
listed here in alphabetical order.
Built-in Functions
A E L R
abs() enumerate() len() range()
aiter() eval() list() repr()
all() exec() locals() reversed()
anext() round()
any() F M
ascii() filter() map() S
float() max() set()
B format() memoryview() setattr()
bin() frozenset() min() slice()
bool() sorted()
breakpoint() G N staticmethod()
bytearray() getattr() next() str()
bytes() globals() sum()
O super()
C H object()
callable() hasattr() oct() T
chr() hash() open() tuple()
classmethod() help() ord() type()
compile() hex()
complex() P V
I pow() vars()
D id() print()
delattr() input() property() Z
dict() int() zip()
dir() isinstance()
divmod() issubclass() _
iter() __import__()
abs(x)
Return the absolute value of a number. The argument may be an integer, a floating point number, or an
object implementing __abs__(). If the argument is a complex number, its magnitude is returned.
aiter(async_iterable)
Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
4/9
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
ascii(object)
As repr(), return a string containing a printable representation of an object, but escape the non-ASCII
characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that
returned by repr() in Python 2.
bin(x)
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression.
If x is not a Python int object, it has to define an __index__() method that returns an integer. Some
examples:
>>>
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
Chr(i)
Return the string representing a character whose Unicode code point is the integer i. For
example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be
raised if i is outside that range.
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as
follows −
5/9
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to the printme()
function in the following ways −
6/9
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call
for that argument. The following example gives an idea on default arguments, it prints default age if it is not
passed −
7/9
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These
arguments are called variable-length arguments and are not named in the function definition, unlike required
and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments.
This tuple remains empty if no additional arguments are specified during the function call. Following is a
simple example −
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
8/9
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print varreturn;
Output is:
10
Output is:
70
60
50
Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for
performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
All the above examples are not returning any value. You can return a value from a function asfollows −
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python −
Global variables
Local variables
This means that local variables can be accessed only inside the function in which they are declared, whereas
global variables can be accessed throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope. Following is a simple example
−
#!/usr/bin/python
total = 0; # This is global variable.# Function
definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z = x + y
print(z)
print("z is of type:",type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
# initializing string
s = "10010"
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using ord(), hex(), oct()
ord(): This function is used to convert a character to an integer.
hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.
# initializing integer
s = '4'
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
# initializing string
s = 'geeks'
Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
Python code to demonstrate Type conversion using dict(), complex(), str()
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.
# initializing integers
a = 1
b = 2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
Higher Order Functions
Because functions are objects we can pass them as arguments to other functions. Functions that can accept
other functions as arguments are also called higher-order functions. In the example below, a function greet is
created which takes a function as an argument.
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
Wrapper function
Wrapper function or decorator allows us to wrap another function in order to extend the behavior of the
wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into
another function and then called inside the wrapper function.
# defining a decorator
def hello_decorator(func):
return inner1
Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
print("square of 2 is :"+str(square(2)))
print("\nThe cube of "+str(square(2))+" is " +str(cube(square(2))))
utput:
square of 2 is :4
The cube of 4 is 64
Python - Modules
A module allows you to logically organize your Python code. Grouping related code into a module makes the
code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can
bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of
a simple module, support.py
When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module. For
example, to import the module support.py, you need to put the following command at the top of the script −
#!/usr/bin/python
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents themodule
execution from happening over and over again if multiple imports occur.
For example, to import the function fibonacci from the module fib, use the following statement −
This statement does not import the entire module fib into the current namespace; it just introducesthe item
fibonacci from the module fib into the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the current namespace;however,
this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the followingsequences −
If the module isn't found, Python then searches each directory in the shell variablePYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable
contains the current directory, PYTHONPATH, and the installation-dependent default.
A Python statement can access variables in a local namespace and in the global namespace. If a local and a
global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary
functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned
a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global
statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the
local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we assign
Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the
local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney() print
Money
The list contains the names of all the modules, variables and functions that are defined in a module. Following
is a simple example −
Live Demo
#!/usr/bin/python
content = dir(math)
print content
[' doc ', ' file ', ' name ', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh','sqrt', 'tan', 'tanh']
Here, the special string variable name is the module's name, and file is the filename from
which the module was loaded.
If locals() is called from within a function, it will return all the names that can be accessed locallyfrom
that function.
If globals() is called from within a function, it will return all the names that can be accessed globally from that
function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys()
function.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload()function.
The reload() function imports a previously imported module again. The syntax of the reload() function is this
−
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing the module
name. For example, to reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application environment that
consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above −
After you add these lines to init .py, you have all of these classes available when you import the Phone
package.
#!/usr/bin/python
Phone.Pots()
Phone.Isdn()
Phone.G3()
In the above example, we have taken example of a single functions in each file, but you can keep multiple
functions in your files. You can also define different Python classes in those files and then you can create your
packages out of those classes.
The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python
runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact
strongly with the interpreter.
Input and Output using sys
The sys modules provide variables for better control over input or output. We can even redirect the input and output to other
devices. This can be done using three variables –
stdin
stdout
stderr
stdin: It can be used to get input from the command line directly. It is used for standard input. It internally calls the input()
method. It, also, automatically adds ‘\n’ after each sentence.
3
Python math Module
Python has a built-in module that you can use for mathematical tasks.
Math Methods
Method Description
math.comb() Returns the number of ways to choose k items from n items without repetition and order
math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter
math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of
that point
math.expm1() Returns Ex - 1
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.perm() Returns the number of ways to choose k items from n items with order and without repetition
math.remainder() Returns the closest value that can make numerator completely divisible by the denominator
import time
What is epoch?
The epoch is the point where the time starts and is platform-dependent. On Windows and most Unix systems, the epoch is
January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch. To check
what the epoch is on a given platform we can use time.gmtime(0).
import time
print(time.gmtime(0))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1,
tm_isdst=0)
ex:-
import time
curr = time.time()
print("Current time in seconds since epoch =", curr)
output:-
Current time in seconds since epoch = 1627908387.764925
import time
Output
Current time: Mon Aug 2 12:45:13 2021