UNIT III - Python
UNIT III - Python
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()
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
Output :
The youngest child is Rahul
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.
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)
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()
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
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.
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))
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)
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))
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)
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
x = math.pi
print(x)
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'
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
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:
my_cart = Supermarket()
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)