Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
379 views

UNIT III - Python

This document discusses Python functions including: 1) Defining functions using the def keyword and calling functions by name. 2) Passing parameters to functions and built-in functions. 3) Variable number of arguments using *args and **kwargs. 4) Scope of variables as global, local, or built-in. 5) Type conversion between integers, floats, and strings using implicit and explicit conversion. 6) Passing functions as arguments to other functions.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
379 views

UNIT III - Python

This document discusses Python functions including: 1) Defining functions using the def keyword and calling functions by name. 2) Passing parameters to functions and built-in functions. 3) Variable number of arguments using *args and **kwargs. 4) Scope of variables as global, local, or built-in. 5) Type conversion between integers, floats, and strings using implicit and explicit conversion. 6) Passing functions as arguments to other functions.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Page |1

UNIT III
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 code that performs a specific
task. There are two types of function in Python
programming:
Standard library functions - These are built-in functions in Python that are available to use.
User-defined functions - We can create our own functions based on our requirements.
Python Function Declaration
The syntax to declare a function is:
def function_name( parameters ):
# code block
return
Here,
def - keyword used to declare a function
function_name - any name given to the
function Parameters - any value passed to
function return (optional) - returns value from a
function Example :
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")

my_function()

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |2

Passing parameters to a Function


 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
From a function's perspective:
 A parameter is the variable listed inside the parentheses in the function definition.
 An argument is the value that is sent to the function when it is called.

The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " India")

my_function("Hello")
my_function("welcome")
0utput :
Hello India
welcome India

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less.
Example
This function expects 2 arguments, and gets 2
arguments: def my_function(fname, lname):
print(fname + " " + lname)

my_function("Hello", "India")
Hello India

Output :
Hello India

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |3

Python Built-in Functions


 Built in functions are the functions that are already created and stored in python.
 These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.

Variable Number of Arguments


 Sometimes, we do not know in advance the number of arguments that will be passed
into a function.
 Python allows us to handle this kind of situation through function calls with number
of arguments.
Non - Keyworded Arguments (*args)
Keyworded Arguments (**kwargs)

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |4

Arbitrary Arguments, *args


 If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
 This way the function will receive a tuple of arguments, and can access the items
accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("raja", "roja", "rahul")

Output :
The youngest child is Rahul

Arbitrary Keyword Arguments, **kwargs


 If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition.
 This way the function will receive a dictionary of arguments, and can access the items
accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter
name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Rajesh", lname = "Kumar")


Output :
His last name is Kumar

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |5

Scope
 A variable is only available from inside the region it is created. This is called scope.
 In Python, there are four types of scopes, which are as
follows: Global Scope
Local Scope
Enclosing Scope 
Built-in Scope
Local Scope
 A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)

myfunc()

Global Scope
 A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
 Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300

def myfunc():
print(x)

myfunc()

print(x)

Global Keyword
 If you need to create a global variable, but are stuck in the local scope, you can use
the global keyword.
 The global keyword makes the variable global.

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |6

Example
If you use the global keyword, the variable belongs to the global scope:
x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

NonLocal or Enclosing Scope


As explained in the example above, the variable x is not available outside the function, but it
is available for any function inside the function:
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()
Built-in Scope
If a Variable is not defined in local, Enclosed or global scope, then python looks for it in the
built-in scope. In the Following Example, 1 from math module pi is imported, and the value
of pi is not defined in global, local and enclosed. Python then looks for the pi value in the
built-in scope and prints the value.
Example
from math import pi
def func_outer():
# pi = 'Not defined in outer pi'
def inner():
# pi = 'not defined in inner pi'
print(pi)
inner()
func_outer()

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |7

Type Conversion
 Type conversion is the convert a data type to a different data type. This is called type
conversion..
 In Python, there are two kinds of type conversion:
Explicit Type Conversion-The programmer must perform this task
manually. Implicit Type Conversion-By the Python program automatically.
Implicit Type Conversion
In implicit Type Conversion, the Python interpreter converts one data type to another
data type automatically during run time. To avoid data loss, Python converts the lower data
type to a higher data type.
The automatic type conversion from one data type to another is called as Type
Coercion. This is also called as Implicit Type Conversion.
Let’s see an example to understand
more: number1 = 10 # integer
number2 = 20.5 # float
sum_addition = number1 +
number2

print(sum_addition) # Output: 30.5


print(type(sum_addition)) # Output: <class 'float'>

Explicit Type Conversion


In explicit Type Conversion, you need to convert the values explicitly with the help of
predefined functions like int(), float(), str(), bool(), etc.
This is also known as typecasting. In this process, there are chances of data loss as you are
converting the value to a lower data type.
Let’s see an example to understand
more: value1 = 10 # integer
value2 = "10" # string
# Type casting value2 of string to
integer value2 = int(value2)
sum_addition = value1 + value2
print(sum_addition) # Output: 20
print(type(sum_addition)) # Output: <class 'int'>

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


Page |8

Passing Functions to a Function


 A function can take multiple arguments, these arguments can be objects,
variables(of same or different data types) and functions.
 Python functions are first class objects.
 In the example below, a function is assigned to a variable. This assignment doesn’t
call the function. It takes the function object referenced by shout and creates a
second name pointing to it, yell.
Example :
def shout(text):
return
text.upper()
print(shout('Hello'))
yell = shout
print(yell('coimbatore'))
Output:
HELLO
COIMBATORE
Higher order function: Since functions are objects, we can pass them as arguments to other
features. Capabilities that take other features as arguments are also referred to as better-order
functions. The subsequent instance creates a Greet feature that takes a feature as an issue.
Example :
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(function):
greeting = function ("Hello, we are created by a higher order function passed as an argume
nt.")
print(greeting)
greet(shout)
greet(whisper)
Output:
HELLO, WE ARE CREATED BY A HIGHER ORDER FUNCTION PASSED AS AN
ARGUMENT.
hello, we are created by a higher order function passed as an argument.
III B.Sc IT – B -- SKACAS UNIT III - PYTHON
Page |9

Mapping Functions in a Dictionary


Python map() applies a function on all the items of an iterator given as input. An
iterator, for example, can be a list, a tuple, a set, a dictionary, a string, and it returns an
iterable map object. Python map() is a built-in function.
Syntax:
map(function, iterator1,iterator2 ...iteratorN)
Parameters
Here are two important
 function: A mandatory function to be given to map, that will be applied to all the
items available in the iterator.
 iterator: An iterable compulsory object. It can be a list, a tuple, etc. You can pass
multiple iterator objects to map() function.
How map() function works?
The map() function takes two inputs as a function and an iterable object. The function
that is given to map() is a normal function, and it will iterate over all the values present in the
iterable object given.
A dictionary in Python is created using curly brackets({}). Since the dictionary is an
iterator, you can make use of it inside map() function. Let us now use a dictionary as an
iterator inside map() function.
Following example shows the working of dictionary iterator inside map()
def myMapFunc(n):
return n*10
my_dict = {2,3,4,5,6,7,8,9}
finalitems = map(myMapFunc, my_dict)
print(finalitems)
print(list(finalitems))
Output:
<map object at
0x0000007EB451DEF0> [20, 30, 40,
50, 60, 70, 80, 90]

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 10

Lambda
 A Lambda Function in Python programming is an anonymous function or a function
having no name.
 It is a small and restricted function having no more than one line. Just like a normal
function, a Lambda function can have multiple arguments with one expression.
 In Python, lambda expressions (or lambda forms) are utilized to construct anonymous
functions. To do so, you will use the lambda keyword (just as you use def to define
normal functions).
 Every anonymous function you define in Python will have 3 essential parts:
o The lambda keyword.
o The parameters (or bound variables), and
o The function body.
 A lambda function can have any number of parameters, but the function body can
only contain one expression.
 Moreover, a lambda is written in a single line of code and can also be invoked
immediately.

Syntax and Examples


The formal syntax to write a lambda function is as given below:
lambda p1, p2: expression
Here, p1 and p2 are the parameters which are passed to the lambda function. You can add as
many or few parameters as you need.

Example
Now that you know about lambdas let’s try it with an example. So, open your IDLE and type
in the following:

adder = lambda x, y: x + y
print (adder (1, 2))

Here is the output:


3

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 11

Python Modules
 A Python module is a file containing Python definitions and statements.
 A module can define functions, classes, and variables.
 A module can also include runnable code.
 Grouping related code into a module makes the code easier to understand and use. It
also makes the code logically organized.
Create a simple Python module
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import Module in Python
We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
Syntax of Python Import
import module
Note: This does not import the functions or classes directly instead imports the module only.
To access the functions inside the module the dot(.) operator is used.
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc

print(calc.add(10, 2))

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
import calc as C

print(C.add(10, 2))

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 12

Standard Modules
The Python interactive shell has a number of built-in functions. They are loaded
automatically as a shell starts and are always available, such as print() and input() for I/O,
number conversion functions int(), float(), complex(), data type
conversions list(), tuple(), set(), etc.
In addition to built-in functions, a large number of pre-defined functions are also
available as a part of libraries bundled with Python distributions. These functions are defined
in modules are called built-in modules.
Built-in modules are written in C and integrated with the Python shell. Each built-in
module contains resources for certain system-specific functionalities such as OS
management, disk IO, etc. The standard library also contains many Python scripts (with the
.py extension) containing useful utilities.
sys Module
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. Let’s consider the below example.
import sys
print(sys.version)
Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
In the above example, sys.version is used which returns a string containing the version of
Python Interpreter with some additional information. This shows how the sys module
interacts with the interpreter. Let us dive into the article to get more information about the sys
module.
math
Built-in Math Functions
The min() and max() functions can be used to find the lowest or highest value in an iterable:
Example
x = min(5, 10, 25)
y = max(5, 10, 25)
Print(x)
print(y)

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 13

The pow(x, y) function returns the value of x to the power of y (xy).


x = pow(4, 3)
print(x)

The Math Module

Python has also a built-in module called math, which extends the list of mathematical
functions.
To use it, you must import the math
module: import math
When you have imported the math module, you can start using methods and constants of the
module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math

x = math.sqrt(64)

print(x)

The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer, and returns the
result:
Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

The math.pi constant, returns the value of PI (3.14...):


Example
import math

x = math.pi

print(x)

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 14

Python time module


The Python time module provides many ways of representing time in code, such as
objects, numbers, and strings. It also provides functionality other than representing time, like
waiting during code execution and measuring the efficiency of your code.
The epoch, then, is the starting point against which you can measure the passage of
time.
You can use time.gmtime() to determine your system’s epoch:
>>> import time
>>> time.gmtime(0)
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)

First, time.time() returns the number of seconds that have passed since the epoch. The return
value is a floating point number to account for fractional seconds:
>>> from time import time
>>> time()
1551143536.9323719
As you saw before, you may want to convert the Python time, represented as the number of
elapsed seconds since the epoch, to a string. You can do so using ctime():
>>> from time import time, ctime
>>> t = time()
>>> ctime(t)
'Mon Feb 25 19:11:59 2019'
Example 2 :
>>> from time import ctime
>>> ctime()
'Mon Feb 25 19:11:59 2019'

The string representation of time, also known as a timestamp, returned by ctime() is


formatted with the following structure:

1. Day of the week: Mon (Monday)


2. Month of the year: Feb (February)
3. Day of the month: 25
4. Hours, minutes, and seconds using the 24-hour clock notation: 19:11:59
5. Year: 2019

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 15

dir() function in Python


dir() is a powerful inbuilt function in Python3, which returns list of the attributes and
methods of any object (say functions , modules,
strings, lists, dictionaries etc.)

Syntax:
dir({object})
 For Class Objects, it returns a list of names of all the valid attributes and
base attributes as well.
 For Modules/Library objects, it tries to return a list of names of all the
attributes, contained in that module.
 If no parameters are passed it returns a list of names in the current local scope.
Example 1

# Python3 code to demonstrate dir() function


# when a module Object is passed as parameter.

import random
# Prints list which contains names of
# attributes in random function
print("The contents of the random library
are::") # module Object is passed as parameter
print(dir(random))
Example 2
class Supermarket:

def dir (self):


return ['customer_name', 'product',
'quantity', 'price', 'date']

my_cart = Supermarket()

# listing out the dir() method


print(dir(my_cart))
Output:
['customer_name', 'date', 'price', 'product', 'quantity']

III B.Sc IT – B -- SKACAS UNIT III - PYTHON


P a g e | 16

Python help() function


The Python help function is used to display the documentation of modules, functions,
classes, keywords, etc.
The help function has the following syntax:
help([object])
Python help() function arguments
object: Call help of the given object.
If the help function is passed without an argument, then the interactive help utility starts up
on the console.
Python help() Example
Let us check the documentation of the print function in the python console.
help(print)
Output:
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

III B.Sc IT – B -- SKACAS UNIT III - PYTHON

You might also like