4. Python Functions, Modules and Packages
4. 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.
conversion
# using tuple(), set(), list()
# initializing
string s =
'geeks'
# 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))
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
Arguments are specified after the function name, inside the parentheses.
def hi(name):
print(name)
hi("MMP")
Output:
MMP
my_function("Purva","Paw
ar") Output:
Purva Pawar
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.
my_function("purva","sandesh","jiya
nsh") Output
The youngest child is sandesh
lname = "mini")
Output
Her last name is mini
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
"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
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
xx=
print(my_function(9))
Output
300
myfunc()
print(x)
Output
300
Example:
hello.py def
SayHello(name):
print("Hello {}! How are
you?".format(name)) return
importing modules
>>> import hello
>>> hello.SayHello("purva")
Output
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name":
"John",
"age": 36,
"country": "Norway"
}
Output:
36
>>>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
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.
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
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
Import NumPy
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
1-D Arrays
or 1-D array. These are the most common and basic arrays.
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.interpolate Interpolation
scipy.optimize Optimization