0% found this document useful (0 votes)
0 views

4. Python Functions, Modules and Packages

Uploaded by

prasaddigole81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

4. Python Functions, Modules and Packages

Uploaded by

prasaddigole81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

3.

Python Functions, Modules and Packages

1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in
which string is if data type is string.

2. float() : This function is used to convert any data type to a floating

point number # Python code to demonstrate Type conversion


# initializing
string s =
"10010"

# printing string converting to


int base 2 c = int(s,2)
print ("After converting to integer base 2 :
", end="") print (c)

# printing string converting


to float e = float(s)
print ("After converting to float : ",
end="") print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0

3. ord() : This function is used to convert a character to integer.

4. hex() : This function is to convert integer to hexadecimal string.

5. oct() : This function is to convert integer to


octal string. # initializing integer
s = '4'

# printing character converting


to integer c = ord(s)
print ("After converting character to integer :
",end="") print (c)

# printing integer converting to


hexadecimal string c = hex(56)
print ("After converting 56 to hexadecimal string :
",end="") print (c)

# printing integer converting to


octal string c = oct(56)
print ("After converting 56 to octal string :
",end="") print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

6. tuple() : This function is used to convert to a tuple.

7. set() : This function returns the type after converting to set.

8. list() : This function is used to convert any data type

to a list type. # Python code to demonstrate Type

conversion
# using tuple(), set(), list()

# initializing
string s =
'geeks'

# printing string converting


to tuple c = tuple(s)
print ("After converting string to tuple :
",end="") print (c)

# printing string
converting to set c = set(s)
print ("After converting string to set :
",end="") print (c)

# printing string
converting to list c = list(s)
print ("After converting string to list :
",end="") print (c)
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']

9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10.str() : Used to convert integer into a string.
11.complex(real,imag) : : This function converts real numbers to
complex(real,imag) number. # Python code to demonstrate Type
conversion
# using dict(), complex(), str()

# initializing integers
a=1
b=2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number :
",end="") print (c)

# printing integer converting to


string c = str(a)
print ("After converting integer to string :
",end="") print (c)

# printing tuple converting to expression


dictionary c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)
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}

4.2 User defined functions: Function definition, function calling, function


arguments and parameter passing, Return statement, Scope of Variables:
Global variable and Local variable.

the user can create its functions which can be called user-defined functions.

In python, we can use def keyword to define the function. The syntax to define a function in python is given
below.

def my_function():
function code
return
<expression>

Function calling

In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function or
the python prompt. To call the function, use the function name followed by the parentheses.

A simple function that prints the message "Hello Word" is given below.

def hello_world():
print("hello

world") hello_world()
Output:

hello world

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses.

def hi(name):
print(name)

hi("MMP")
Output:
MMP

def my_function(fname, lname):


print(fname + " " +
lname)

my_function("Purva","Paw
ar") Output:
Purva Pawar

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.

If the number of arguments is unknown, add a * before the


parameter name: def my_function(*kids):
print("The youngest child is " + kids[1])

my_function("purva","sandesh","jiya
nsh") Output
The youngest child is sandesh

If the number of keyword arguments is unknown, add a double ** before the


parameter name: def my_function(**kid):
print("Her last name is " +
kid["lname"]) my_function(fname = "nitu",

lname = "mini")
Output
Her last name is mini

Default Parameter Value

If we call the function without argument, it uses the default value:

def my_function(country =
"Norway"): print("I am from
" + country)

my_function("Swede
n")
my_function("India")
my_function()
my_function("Brazil"
) Output
I am from
Sweden I am
from India
I am from
Norway I am
from Brazil

Passing a List as an Argument


def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana",

"cherry"] my_function(fruits)
Outp
ut
apple
bana
na
cherr
y

Return statement
def
my_function(x

): return 5 * x

print(my_function(3))

print(my_function(5))
print(my_function(9))

Output

15

25

45

Scope of Variables: Global variable and Local variable.

Local variable

A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function.
A variable created inside a function is available inside that
function: def myfunc():
x = 300
print(x)

myfunc
()
Output

300

Global variable

Global variables are available from within any scope, global and local.
A variable created outside of a function is global and can be used
by anyone: x = 300

def myfunc():
print(

x) myfunc()

print(
x)
Outpu
t 300

300
The global keyword makes the variable

global. def myfunc():

global

xx=
print(my_function(9))

Output
300

myfunc()
print(x)

Output
300

Modules: Writing modules


Shown below is a Python script containing the SayHello() function. It is saved as hello.py.
definition of

Example:

hello.py def

SayHello(name):
print("Hello {}! How are
you?".format(name)) return

importing modules
>>> import hello

>>> hello.SayHello("purva")

Output

Hello purva! How are you?

importing objects from modules


To import only parts from a module, by using the from keyword.

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name":
"John",
"age": 36,
"country": "Norway"
}

Import only the person1 dictionary from the module:

from mymodule import


print(x)
person1 print
Output
(person1["age"])

Output:
36

Python built-in modules(e.g. Numeric and Mathematical module, Functional programming


module)
Python - Math Module

>>> import math


>>>math.pi
3.141592653589793

>>>math.log(10)
2.302585092994046

>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257

>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996

Namespace and Scoping.


 A namespace is a mapping from names to objects.
 Python implements namespaces in the form of dictionaries.
 It maintains a name-to-object mapping where names act as keys and the objects as values.
 Multiple namespaces may have the same name but pointing to a different variable.

 A scope is a textual region of a Python program where a namespace is directly accessible.

 Local scope

 Non-local scope

 Global scope

 Built-ins scope
1. The local scope. The local scope is determined by whether you are in a class/function
definition or not. Inside a class/function, the local scope refers to the names defined inside
them. Outside a class/function, the local scope is the same as the global scope.

2. The non-local scope. A non-local scope is midways between the local scope and the
global scope, e.g. the non-local scope of a function defined inside another function is the
enclosing function itself.

3. The global scope. This refers to the scope outside any functions or class definitions. It
also known as the module scope.

4. The built-ins scope. This scope, as the name suggests, is a scope that is built into Python.
While it resides in its own module, any Python program is qualified to call the names
defined here without requiring special access.

# var1 is in the global


namespace var1 = 5
def some_func():

# var2 is in the local


namespace var2 = 6
def some_inner_func():

# var3 is in the nested


local # namespace
var3 = 7

Python Packages : Introduction


Python has packages for directories and modules for files. As a directory can contain sub-
directories and files, a Python package can have sub-packages and modules.

init .py
A directory must contain a file named in order for Python to consider it as a package. This file can
be
left empty but we generally place the initialization code for that package in this file.

Steps:
 First create folder game.
 Inside it again create folder sound.
 Inside sound folder create load.py file.
 Inside sound folder create pause.py file.
 Inside sound folder create play.py file.
 Import package game and subpackage sound(files:load,pause,play)
Importing module from a package
import game.sound.load
Now if this module contains a function load( we must use the full name to
named ), reference it.

game.sound.load.load()

Math package:
>>> import math
sin, cos and tan ratios for the angle of 30 degrees (0.5235987755982988 radians):
>>>math.pi
3.141592653589793

sin, cos and tan ratios for the angle of 30 degrees (0.5235987755982988 radians):
>>math.sin(0.5235987755982988)

0.49999999999999994

>>>math.cos(0.5235987755982988

) 0.8660254037844387

>>>math.tan(0.5235987755982988

) 0.5773502691896257

NumPy is a python library used for working with arrays.

NumPy stands for Numerical Python.

Why Use NumPy ?

In Python we have lists that serve the purpose of arrays, but they are slow to

process. NumPy aims to provide an array object that is up to 50x faster that

traditional Python lists.

 Install it using this command:

C:\Users\Your Name>pip install numpy

Import NumPy

Use a tuple to create a NumPy array:


0-D Arrays

0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

Create a 0-D array with value 42

1-D Arrays

An array that has 0-D arrays as its elements is called uni-dimensional

or 1-D array. These are the most common and basic arrays.

Create a 1-D array containing the values 1,2,3,4,5:


Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:

SciPy package

SciPy, pronounced as Sigh Pi, is a scientific python open source, distributed under the BSD
licensed library to perform Mathematical, Scientific and Engineering Computations..

The SciPy library depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. SciPy Sub-packages
 SciPy consists of all the numerical code.
 SciPy is organized into sub-packages covering different scientific computing
domains. These are summarized in the following table −

scipy.cluster Vector quantization / Kmeans

scipy.constants Physical and mathematical constants

scipy.fftpack Fourier transform

scipy.integrate Integration routines

scipy.interpolate Interpolation

scipy.io Data input and output

scipy.linalg Linear algebra routines

scipy.ndimage n-dimensional image package

scipy.odr Orthogonal distance regression

scipy.optimize Optimization

scipy.signal Signal processing

scipy.sparse Sparse matrices

scipy.spatial Spatial data structures and algorithms

scipy.special Any special mathematical functions


scipy.stats Statistics

Matplotlib is a plotting library for the Python programming language


and its numerical mathematics extension NumPy.
It provides an object-oriented API for embedding plots into
applications using general-purpose GUI toolkits like Tkinter,
wxPython, Qt, or GTK+ ...... SciPy makes use of Matplotlib.

Pandas is used for data manipulation, analysis and cleaning. Python


pandas is well suited for different kinds of data, such as:

 Tabular data with heterogeneously-typed columns


 Ordered and unordered time series data
 Arbitrary matrix data with row & column labels
 Any other form of observational or statistical data sets

You might also like