PWP - Chapter 4 PDF
PWP - Chapter 4 PDF
PWP - Chapter 4 PDF
Introduction:
Vishal Chavre
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
output
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
# initializing string
s = "10010"
Vishal Chavre
Example 2:-
# Python code to demonstrate Type conversion
# using ord(), hex(), oct()
# initializing integer
s = ‘A'
# 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 : 65
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
Example 3:-
# Python code to demonstrate Type conversion using tuple(),
set(), list()
# initializing string
s = ‘hello'
# 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 : ('h', 'e', 'l', 'l', 'o')
After converting string to set : {'l', 'e', 'o', 'h'}
After converting string to list : ['h', 'e', 'l', 'l', 'o']
Example 4:-
# 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}
Parameter values-
< - Left aligns the result within the available space
e.g.
x=10.23456
print(format(x,"<10.2f"))
Output:
‘10.23 ‘
> - Right aligns the result within the available space
e.g.
x=10.23456
print(format(x,“>10.2f"))
Output:
‘ 10.23 ‘
^ - Center aligns the result within the available space
e.g.
x=10.23456
print(format(x,“^10.2f"))
Output:
‘ 10.23 ‘
+, - - Use a sign to indicate if the result is positive or negative
e.g.
x=10.23456
y=-10.23456
print(format(x,"+"))
print(format(y,"-"))
Output:
+10.23456
-10.23456
, - Use a comma as athousand sepeartor
e.g.
x=10000000
print(format(x,","))
Output:
10,000,000
_ - Use a underscore as a thousand seperator.
e.g.
x=10000000
print(format(x,"_"))
Output:
10_000_000
b - binary format
e.g.
x=10
Vishal Chavre
print(format(x,"b"))
Output:
1010
% – Percentage format
x=100
print(format(x,“%"))
Output:
10000.000000%
>10s - String with width 10 in left justification
e.g.
x=“hello”
print(format(x,“>10s"))
Output:
‘ hello’
<10s - String with width 10 in right justification
x=“hello”
print(format(x,“<10s"))
Output:
‘hello ‘
Built-In functions(Mathematical):
• These are the functions which doesn’t require any external code
file/modules/ Library files.
• These are a part of the python core and are just built within the
python compiler hence there is no need of importing these
modules/libraries in our code.
min()- Returns smallest value among supplied arguments.
e.g. print(min(20,10,30))
o/p 10
max()- Returns largest value among supplied arguments.
e.g. print(max(20,10,30))
o/p 30
pow()- Returns the value of x to the power of y.
e.g. print(pow(2,3))
o/p 8
round()- Returns a floating point number that is rounded version of
the specified number, with the specified number of decimals.
The default number of decimals is 0, i.e it will return nearest
integer.
e.g. print(round(10.2345))
o/p 10
print(round(5.76543))
o/p 6
print(round(5.76543,2))
o/p 5.77
abs()- Returns the non negative value of the argument value.
e.g. print(abs(-5))
o/p 5
Function Definition:
• Function blocks starts with the keyword def taken after by the
function name and parentheses().
• Any input parameters or arguments should be put inside these
brackets.
• The first statement of a function can be optional statement- the
documentation string of the function or doc string.
• The code block inside each capacity begins with a colon(:) and
is indented.
• The statement return[expression] exits a function, alternatively
going back an expression to the caller. A return statemnt with
no arguments is the same as return None.
Function Calling:
The def statement only creates a function but does not call it.
After the def has run, we call the function by adding parentheses
after the function’s name.
Example:
def square(x): #function definition
return x*x
square(4) # function call
output:
16
Vishal Chavre
string = "Hello"
def test(string):
test(string)
Output:
def add_more(list):
list.append(50)
mylist = [10,20,30,40]
add_more(mylist)
Output:
There are four types of arguments using which can be called are
required arguments, keyword arguments, default arguments and
variable length arguments.
Required Arguments:
def printme(str):
print(str)
return
mylist=[10,20,30]
Output:
printme()
Keyword Arguments:
# Keyword Arguments
def printme(str):
"This prints a passed string into this function"
print(str)
return
printme(str="My string")
Output:
My string
def printinfo(name,age):
print("Name: ",name)
print("Age: ",age)
return
printinfo(age=35,name="Amol")
Output:
Name: Amol
Age: 35
Default Arguments:
def printinfo(name,age=35):
print("Name: ",name)
print("Age: ",age)
return
printinfo(age=40,name="Amol")
printinfo(name="Kedar")
Output:
Name: Amol
Age: 40
Name: Kedar
Age: 35
def printadd(farg,*args):
sum=0
for i in args:
sum+=i
return
Vishal Chavre
# Call printadd function
printadd(5,10)
printadd(5,10,20,30)
Output:
Output is: 5
Output is: 5
Return Statement:
Example:
def fact(n):
prod=1
while n>=1:
prod*=n
n-=1
return prod
for i in range(1,11):
print('Factorial of {} is {}'.format(i,fact(i)))
Output:
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
Factorial of 10 is 3628800
Scope of Variables:
Local variables:
Global variables:
def myfunction():
a+=1
print(a)
# Call myfunction
myfunction()
print(a)
Output:
print(a)
Vishal Chavre
def myfunction():
print('a= ',a)
print('b= ',b)
# Call myfunction
myfunction()
print(a)
print(b)
Output:
a= 1
b= 2
print(b)
Advantages of modules –
Writing Module:
Create p1.py file and add the below code in the file
def add(a,b):
result=a+b
return result
def sub(a,b):
result=a-b
return result
def mul(a,b):
result=a*b
return result
def div(a,b):
result=a/b
return result
import p1
print("Addition= ",p1.add(10,20))
print("Subtraction= ",p1.sub(10,20))
print("Multiplication= ",p1.add(10,20))
print("Division= ",p1.add(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 30
Division= 30
Importing Modules:
e.g.
Import employee
from p1 import *
print("Addition= ",add(10,20))
print("Multiplication= ",mul(10,20))
Output:
Addition= 30
Multiplication= 200
print("Addition= ",add(10,20))
print("Subtraction= ",sub(10,20))
Output:
Addition= 30
Subtraction= -10
Syntax:
import p1 as m
Vishal Chavre
print(‘addition is :’,m.add)
2. math(Mathematical functions)
5. fractions(Rational numbers)
import math
# in math module
print math.sqrt(25)
print math.pi
print math.degrees(2)
print math.radians(60)
# Sine of 2 radians
print math.sin(2)
print math.cos(0.5)
print math.tan(0.23)
# 1 * 2 * 3 * 4 = 24
print math.factorial(4)
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
cmath module
Example
c=2+2j
print(exp(c))
print(log(c,2))
print(sqrt(c))
Output:-
(-3.074932320639359+6.71884969742825j)
(1.5000000000000002+1.1330900354567985j)
Vishal Chavre
(1.5537739740300374+0.6435942529055826j)
Decimal module:
• These are just the floating point numbers with fixed decimal
points.
Example:
print(Decimal(121))
print(Decimal(0.05))
print(Decimal('0.15'))
print(Decimal('0.012')+Decimal('0.2'))
print(Decimal(72)/Decimal(7))
print(Decimal(2).sqrt())
Output:
121
0.050000000000000002775557561562891351059079170227050781
25
0.15
0.212
10.28571428571428571428571429
1.414213562373095048801688724
Fractions module:
Example:
import fractions
fract=fractions.Fraction(num,decimal)
print(fract)
Output:
3/2
2/5
15/2
Random module:
Example:
import random
print(random.random())
print(random.randint(10,20))
Output:
0.8709966760966288
16
Statistics module:
• It provides access to different statistics functions such as mean,
median, mode, standard deviation.
Example:
import statistics
print(statistics.mean([2,5,6,9]))
print(statistics.median([1,2,3,8,9]))
print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6]))
print(statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5]))
Output:
5.5
3
Vishal Chavre
2
1.3693063937629153
1. Itertools
2. Functools
3. operator
Itertools Module:
Example:
print(value)
output:
1.3
2.51
3.3
c++
python
java
functools Module:
Example:
def multiplier(x,y):
return x*y
return x*y
def doubleIt(x)
return multiplier(x,2)
def tripleIt(x):
return multiplier(x,3)
def multiplier(x.y):
return x*y
double=partial(multiplier,y=2)
triple=partial(multiplier,y=3)
print(“Double of 5 is {}’.format(double(5)))
print(“Triple of 5 is {}’.format(triple(5)))
Output:
Double of 5 is 10
Triple of 5 is 15
Operator Module:
Types of Namespace:
def scope():
print(global_var)
print(local_var)
scope()
print(global_var)
Output:
30
40
30
Introduction-
• Suppose we have developed a very large application that
includes many modules. As the number of modules grows, it
becomes difficult to keep track of them as they have similar
names or functionality.
• Create file p1.py in the mypkg directory and add this code
def m1():
print("First Module")
• Create file p2.py in the mypkg directory and add this code
def m2():
print("second module")
p2.m2()
Output-
First Module
second module
Math:
import math
print(math.pi)
o/p
3.141592653589793
module is e.
e.g
import math
print(math.e)
o/p
2.718281828459045
NumPy:
Array Object:
Example:
import numpy as np
a=np.array([10,20,30])
print(a)
arr=np.array([[1,2,3],[4,5,6]])
print(arr)
Vishal Chavre
type(arr) # <class ‘numpy.ndarray’>
Example:
import numpy as np
arr1=np.array([1,2,3,4,5])
arr2=np.array([2,3,4,5,6])
print(arr1)
Reshaping of Array:
Example:
import numpy as np
arr=np.array([[1,2,3],[4,5,6]])
a=arr.reshape(3,2)
print(a)
Output:
Vishal Chavre
([[1,2],
[3,4],
[5,6]])
Slicing of Array:
• Slicing is basically extracting particular set of elements from an
array. Consider an array([(1,2,3,4),(5,6,7,8)])
e.g.
import numpy as np
a=np.array([(1,2,3,4),(5,6,7,8)])
print(a[0,2]) # 3
e.g. When we need 2nd element from 0 and 1 index of the array
import numpy as np
a=np.array([(1,2,3,4),(5,6,7,8)])
print(a[0:,2]) # [3 7]
• SciPy uses NumPy arrays as the basic data structure and come
with modules for various commonly used tasks in scientific
programming, including linear algebra, integration (calculus),
ordinary differential equation solving and signal processing.
import numpy as np
a=np.array([[1.,2.],[3.,4.]])
o/p
array([[-2.,1.],[1.5,-0.5]])
Vishal Chavre
e.g. using linalg sub package of SciPy
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
o/p
0.0
cb=cbrt([81,64])
o/p
array([4.32674871, 4. ])
Matplotlib:
e.g.
x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
plt.plot(x,y)
plt.show()
e.g.
x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
plt.plot(x,y)
plt.show()
Vishal Chavre
output:
• The plot function takes the value from x and y datasets and plot
the graph for the same. While providing the dataset you need to
remember that the number of elements in x and y dataset should
be equal.
Example-
x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
plt.plot(x,y)
plt.xlabel(‘X-axis’)
plt.ylabel(‘Y-axis’)
plt.title(‘First Graph’)
plt.show()
output:
Vishal Chavre
Scatter Plot:
• This graph will only mark the point that is being plotted in the
graph.
x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
plt.scatter(x,y)
plt.show()
output:
Bar Graph:
e.g.
x=[2,4,8,10]
y=[2,8,8,2]
plt.xlabel('X-axis')
plt.text(0.5,0,'X-axis')
plt.ylabel('Y-axis')
plt.title('Graph')
plt.text(0.5,1.0,'Graph')
plt.bar(x,y,label="Graph",color='r',width=0.5)
plt.show()
output:
import numpy as np
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]
plt.yticks(y_pos, objects)
plt.xlabel('Usage')
plt.show()
Output-
Vishal Chavre
• NumPy arange() is an inbuilt numpy function that returns a
ndarray object containing evenly spaced values within the given
range. The arange() returns an array with evenly spaced elements as
per the interval. The interval mentioned is half opened i.e. [Start, Stop)
Example:
import numpy as np
# data to plot
n_groups = 4
# create plot
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
plt.ylabel('Scores')
plt.title('Scores by person')
plt.legend()
plt.tight_layout()
plt.show()
Output-
Pandas:
1. Series
2. Data frames
3. Panel
Series-
e.g.
import pandas as pd
data=[1.1,2.1,3.1,4.1,5.1,6.1,7.1,8.1]
df=pd.Series(data)
Output-
0 1.1
1 2.2
2 3.1
3 4.1
4 5.1
5 6.1
6 7.1
7 8.1
dtype: float64
DataFrame-
import pandas as pd
dict1={'a':1.1,'b':2.1,'c':3.1,'d':4.1}
df=pd.DataFrame(data)
print(df)
Output-
Col1 Col2
a 1.1 5.1
b 2.1 6.1
c 3.1 7.1
d 4.1 8.1
Example:-
import pandas as pd
s1=pd.Series([1,3,4,5,6,2,9])
s2=pd.Series([1.1,3.5,4.7,5.8,2.9,9.3,8.9])
s3=pd.Series([‘a’,’b’,’c’,’d’,’e’,’f’,’g’])
data={‘first’:s1,’second’:s2,’third’:s3}
dfseries=pd.DataFrame(data)
print(dfseries)
Output-
0 1 1.1 a
1 3 3.5 b
2 4 4.7 c
3 5 5.8 d
4 6 2.9 e
5 2 9.3 f
6 9 8.9 g
Panel-
data: The data can be of any form like ndarray, list, dict, map,
DataFrame
import pandas as pd
import numpy as np
data = np.random.rand(2,4,5)
p = pd.Panel(data)
print p
Output:
<class 'pandas.core.panel.Panel'>
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
import pandas as pd
import numpy as np
p = pd.Panel(data)
print(p)
Output:
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2
message.py
def sayhello(name):
return
mathematics.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
p1.py
message.sayhello("Amit")
x=mathematics.power(3,2)
print("power(3,2) :",x)
Output
Vishal Chavre
Hello Amit
power(3,2) : 9
test.py
sayhello("Amol")
x=power(3,2)
Vishal Chavre
print("power(3,2): ",x)
Output-
Hello Amol
power(3,2): 9
Vishal Chavre