Sunteți pe pagina 1din 101

MHM’s Outcome Based

Education

mhmeducations.com
mhmeducations.com
Let’s Talk with
Python

Piyush Dave
mhmeducations.com
Some point need to know about
Python
• HLL
• relatively simple
• Free and Open-Source
• Large Standard Library
• GUI
• IOT Opportunities
• Python ranked #1 on the IEEE Spectrum list of top
programming languages for 2019
mhmeducations.com
Big Companies Using Python
NASA Disqus
Google Hike
Nokia Spotify
IBM Udemy
Yahoo! Maps Shutterstock
Walt Disney Feature Uber
Animation Amazon
Facebook Mozilla
Netflix Dropbox
Expedia Pinterest
Reddit YoutubeQuora
MIT
mhmeducations.com
Stage 1 Stage 2

1. Introduction 1. Module
2. Syntax 2. Classes
3. Statement, Indentation, and 3. Methods
Comments 4. Iterators
4. Variables and Data types 5. Decorators
5. Operators 6. Generators
6. Numbers
7. Strings Stage3
8. List
9. Tuples 1. Web framework
10. Library like Numpy, Scipy, Pandas, 2. Machine Learning
Matplotlib 3. Deep learning
4. Artificial Intelligence
5. Relational Database
mhmeducations.com
mhmeducations.com
Lets talk to Python……
we will give some task to Python

Let‟s Play

First Program
mhmeducations.com
• print('hello')
• print("hello")
• print('''hello''')
• print('''hello''')
• print('''MHM's Outcome based Education''')
• print(''' MHM's “Outcome based Education“ ''')

mhmeducations.com
x=1
if x = = 1:
# indented four spaces
print("x is 1.")
print("hello")
mhmeducations.com
Variables and Types
• Variable is Container (Name which hold
values)
• Data Type:- There are many but don‟t need to
worry about it…..Defining Data types Python
is very easy

mhmeducations.com
• a=4 • a+b
• a==b
• a (press enter key) • a!=b
• type(a) • a+=b
• Check Content
• b= 5.6 of a and b
• print(b) • a is b
• a is not b
• type(b)
mhmeducations.com
• • a=„100‟
• x=“Hello” a,b=100, 5.6
• type(a)
• a
• type(x) • Int(a)
• b • float(a)
• y=„world‟ • print(type(a)) • a=5
• type(a)
• x+y • x,y = • b=5.5
• y=„ world‟ "python",3 • type(b)
• x+y (error) • c=a*b
• x+y • x+str(y)
• type(c)
mhmeducations.com
More important Types
a= (1,2,3,4)
type(a) a= [1,2,3,4]
a=1,2,3,4 type(a)
type(a)
Important

a= {1,2,3,4} a={1:2,2:3}
type(a) type(a)
mhmeducations.com
Bool:- converts a value to Boolean
(True or False)

mhmeducations.com
• test=[ ] • test=[1] • test=1 • test=True
• bool(test) • bool(test)
• test=( ) • test=(2) • bool(test) • bool(test)
• bool(test) • bool(test) • test=3.5 • test=False
• test={} • test={3} • bool(test) • bool(test)
• bool(test) • bool(test)
• test=„hello‟
• test=None • test= „‟
• bool(test) • bool(test) • bool(test)

mhmeducations.com
mystring = “hello”
print("String: %s" % mystring)
myfloat = 3.5
print("Float: %f " % myfloat)
myint = 100
print("Integer: %d" % myint)

mhmeducations.com
name = "John“
age = 23
height = 165.44
print("%s is %d years old." % (name, age))
print("%s have %f cm height." % (name, height))

mhmeducations.com
How to take input in python
• Asking Input from User

mhmeducations.com
• a=input() • Let Open Editor window
• Python wait for User • a=input()
Input • Python wait for User
• print(a) Input (Confusing For any
• type(a) one)
• Int(a) • Solution
• print(„Enter Input‟)
a=input()
mhmeducations.com
Numerical Operator

+, -, *, / etc

mhmeducations.com
• a= 10
• b=5 • a=“hello”
• a+b • a*10
• a-b • a=“ hello”
• a*b • a*10
• a/b
• a=[1,2,3,4]
• a//b
• a%b • a*4
• a**b
mhmeducations.com
Logical Operator

AND, OR, NOT

mhmeducations.com
• a=10 • a= True
• b=15 • b= False
• bin(a&b) • not a
• bin(a|b) • not b
• bin(a^b) • a and b
• a or b
mhmeducations.com
Conditions
Greater than, Equal to, Smaller than

mhmeducations.com
• a=5
• b=4
• a>b
• a<b
• a>=b
• a<=b
• a = =b
• a is b
• a is not b
mhmeducations.com
Data type Conversation
• Lets travel from one data type to other

mhmeducations.com
• Int(56.56)
• float(44) • chr(65)
• a=“hello” • chr(90)
• type(a)
• a=tuple("hello") • chr(97)
• a (press enter) • chr(122)
• b=list(“hello”)
• b (press enter) • ord(„A‟)
• a[2] • hex(16)
• b[2]
• a[2]="p" • oct(34)
• b[2]="p" • bin(15)
mhmeducations.com
Numerical Functions
• Math Library
• Inbuilt Math Function

mhmeducations.com
• import math • math.e
• abs(5)
• math.exp(7)
• abs(-5)
• math.sqrt(25)
• math.ceil(35.74)
• math.ceil(-35.74)
• math.floor(16.94)
• math.floor(-16.94)
mhmeducations.com
• math.log(5) • math.modf(11.971)
• math.pow(4,2)
• math.log10(2)
• math.hypot(3,4)
• max(3,5,7,1,10) • math.pi
• min(4,7,56,1,-9) • math.degrees(6)
• round(17.4646,2) • math.radians(343.77
467707849394)
mhmeducations.com
String
• Lets Play with Sentences / Statements

mhmeducations.com
• #Slice
• var = "Python is best"
• var[0] • #use of %
• a = "Hello world!“ • name = 'python'
• print(a[3:7])
• a = "Hello world!“ • version = 3
• print(a[::-1]) • print('%s %d'
• #Membership
%(name,version))
• var="python"
• "p" in var
mhmeducations.com
#replace
• #concatenates of
2 strings • old = 'I like you'
• var1="East" • new = old.replace('like',
'love')
• var2="West" • new (press enter)
• var1+var2
• new.upper()
• #Repeat • new.lower()
• var1="Rama“ • new.capitalize()
• 3*var1 mhmeducations.com
#Split
new='language' #join
new.split('a') ("g".join("Python"))

#Replace #reverse
x = "C Language"
new="python"
x= x.replace("C
Language","Python") “”.join(reversed(new))

a='hello'
len(a)
mhmeducations.com
a = "Hello world!“ str="www.google.com"
print(a.index("o")) str.endswith('.com')
str.endswith('.net')
a = "Hello world!“ len(str)
print(a.count("l")) str="!!!!!!!!! hello“
str.lstrip('!')
a = "Hello world!“ str="hello!!!!!!!!!“
b = a.split(" ") str.rstrip('!')
mhmeducations.com
Membership
• Are you part of me

mhmeducations.com
• a= “i live in • tuple = (3,4,5,6,7,9)
india”
• 3 in tuple
• “india” in a
• 10 not in tuple
• “USA” in a
• Set = {3,4,5,6,7}
• list = [4,5,6,7,8]
• 2 in set
• 4 in list
• dis = {2:1,3:4}
• 9 in list
• 4 in dis
• 3 in dis
mhmeducations.com
List
Store many thing in one variable

mhmeducations.com
• list= [9,8,6,4,3,2] • list.append(100)
• list (Press Enter)
• list (Press Enter)
• list[0]
• list[5] • for x in list:
• list[0:4] print(x)
• list[1:] • list2=[2,3,4,[1,2,3],'apple']
• list[:]
• list[-1] • list2
• list1=list[2:] • list2[3]
• list+list1
mhmeducations.com
• colors=['red','green','blue']
• days=['Monday','Tuesday',
'Wednesday',4,5,6,7.0]
• languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
• languages[0]
• languages=[('English','Albanian'),'Gujarati','Hindi','Romanian','S
panish']
• languages[0]
• languages[0][0]
• type(languages[0])
• languages[0][0]='Albanian'
mhmeducations.com
• indices=['zero','one','two','three','four','five']
• indices[2:4]
• indices[1:-2]
• indices[:-2]
• indices[-2:-1]
• indices[-1:-2]
• del indices
• print(indices)
mhmeducations.com
• a=[[[1,2],[3,4],5],[6,7]] • even=[2,5,6,7100]
• len(even)
• print(a)
• max(even)
• a[0][1][1] • max(['1','2','3'])
• a,b=[3,1,2],[5,4,6] • max([2,'1','2'])
• a+b • min(even)
• a*3 • sum(even)
• 1 in a • a=['1','2','3']
• sum(a)
• 7 not in a
mhmeducations.com
• a=[3,1,2]
• sorted(a)
• list("abc")
• list(2)
• a=[2,3,3,4,5,6,7]
• a.append(4)
• a.insert(3,5)
• a.remove(2)
• a.pop(3)
mhmeducations.com
Program:- Find the length of the list and simply
swap the first element with (n-1)th element.

newlist=[4,5,6,7,8]
size=len(newlist)
temp = newlist[0]
newlist[0] = newlist[size - 1]
newlist[size - 1] = temp
mhmeducations.com
Tuple
• Same as List but immutable

mhmeducations.com
• tuple= (2,3.4,"hello",6+j6)
• tuple (press enter)
• tuple[3]
• tuple[3]=5
• tuple*3
• tuple[-1]

mhmeducations.com
#packing and unpacking

x= ("MHM",2019,"Education")
(company, year, profile)=x
print(company)
print(year)
print(profile)

mhmeducations.com
• a=(1) • a=3,4,5,6,[3,4]
• type(a)
• a[4]
• a=(1,)
• a[4][0]=10000
• type(a)
• a=1, • print(a)
• type(a) • a=((1,2,3),(4,(5,6)))
• my_tuple=(1,2,3,[4,5]) • a[1][1][1]
• my_tuple[3]
mhmeducations.com
a=(2,8)
b=(3,4)
if (a>b):
print("a is greater")
else:
print("b is greater")

mhmeducations.com
Dictionary
• Keys and Values

mhmeducations.com
phonebook = {"Ram" : 956565656, "mick" :
9388658686,"Jill" : 767676767}
Or
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781

mhmeducations.com
• "Ram" in phonebook
• 956565656 in phonebook
• phonebook.pop("Ram")
• phonebook (press enter)
• del phonebook[“mick"]
• phonebook (press enter)

mhmeducations.com
phonebook = {"John" : 938477566,"Jack" :
938377264,"Jill" : 947662781}
for name, number in phonebook.items():
print("Phone number of %s is %d" %
(name, number))

mhmeducations.com
Set
• Unordered set of distinct Value

mhmeducations.com
• a={1,'t',3,'r', 5,'yes'}
• a={1,'t',3,'r', 5,'yes',3}
• b={2,'r',5,'No', 8,'yes'}
• a-b
• b-a
• a&b
• a|b
mhmeducations.com
Date and Time Function

mhmeducations.com
• import time
• time.sleep(10)
• time.time()
• time.localtime(time.time())
• time.asctime()
• tuple=(1987,9,4,0,0,0,0,0,0)
• time.mktime(tuple)
• time.localtime(time.mktime(tuple))
mhmeducations.com
• Import calendar
• print(calendar.month(2019,8))
• print(calendar.calendar(2019))
• calendar.isleap(2019)
• calendar.isleap(2016)

mhmeducations.com
How to Create, Edit, Write, Read
Text File using Python?

mhmeducations.com
f=open("pnd.text","w")
f.write("This is First
line\n") f=open("pnd.text","r")
f.close() if f.mode=="r":
contents = f.read()
f=open("pnd.text","a+")
print(contents)
f.write("This is Second
line")
f.close()
mhmeducations.com
Exception Handling in Python

mhmeducations.com
print(“num”) print(“num”)
num=input() num=input()
print(“den”)
print(“den”)
den=input()
den=input() try:
res= int(num)/int(den) res= int(num)/int(den)
print(res) except:
print(„den cannot be 0‟)
else:
print(res)
mhmeducations.com
Generation of Random Number
• import random
• print(random.randint(100,500))

mhmeducations.com
1. Range
2. for loop

mhmeducations.com
• # Prints out the numbers 0,1,2,3,4
• for x in range(5):
print(x)
• # Prints out 3,4,5
• for x in range(3, 6):
print(x)
• # Prints out 3,5,7
• for x in range(3, 8, 2):
print(x)
mhmeducations.com
words= "piyush"
for word in words:
print(word)

mhmeducations.com
While Loop

mhmeducations.com
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
print(“hello”)

mhmeducations.com
Continue

mhmeducations.com
for x in range(10):
if x % 2 == 0:
continue
print(x)

mhmeducations.com
for var in range(1,16):
if(var in range(9,14)):
continue
else:
print(var)

mhmeducations.com
Break

mhmeducations.com
while (1):
print("enter a digit")
num=input()
var=str(num)
if (ord(var) in range (48,58)):
break
print("you entered BCD")

mhmeducations.com
Basic Programs
Let‟s Code

mhmeducations.com
1. Addition of two Number
2. Check Number is Positive or Negative
3. Check Alphabet
4. Leap Year
5. Guess a Number
6. Simple Calculator
7. Swap Number
8. Table
mhmeducations.com
How to Install Library
• Type in command Prompt
1. python -m pip install numpy
2. python -m pip install scipy
3. python -m pip install matplotlib
4. python -m pip install pandas

mhmeducations.com
Numpy library

mhmeducations.com
import numpy as np
c = np.full((2,2), 7) # Create a constant
a = np.zeros((2,2)) # Create an array of array
all zeros print(c)
print(a)
d = np.eye(2) # Create a 2x2
b = np.ones((1,2)) # Create an array of identity matrix
all ones print(d)
print(b)
e = np.random.random((2,2)) # Create
c = np.full((2,2), 7) # Create a constant an array filled with random values
array print(e)
print(c)
mhmeducations.com
Find the elements of a that are bigger than 2

a = np.array([[1,2], [3, 4], [5, 6]])


bool_idx = (a > 2)
print(bool_idx)
print(a[bool_idx])
print(a[a > 2])
mhmeducations.com
# Element wise arithmetic operation
import numpy as np print(x * y)
x = np.array([[1,2],[3,4]]) print(np.multiply(x, y))
y = np.array([[5,6],[7,8]]) print(x / y)
print(np.divide(x, y))
print(x + y) print(np.sqrt(x))
print(np.add(x, y))
print(x - y)
print(np.subtract(x, y))

mhmeducations.com
Compute sum of all elements or
row or column
import numpy as np

x = np.array([[1,2],[3,4]])

print(np.sum(x))
print(np.sum(x, axis=0))
print(np.sum(x, axis=1))
mhmeducations.com
# Compute the x and y coordinates for points on sine and
cosine curves
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 2 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
mhmeducations.com
plt.show()
scipy library

mhmeducations.com
#Find cubic root of 27 using cbrt() function

from scipy.special import cbrt


cb = cbrt(27)
print(cb)

mhmeducations.com
#define exp10 function and pass value in its

from scipy.special import exp10


exp = exp10(2)
print(exp)

mhmeducations.com
#Frequency in terms of Hertz
#matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import scipy
#Frequency in terms of Hertz
fre = 5
#Sample rate
fre_samp = 50
t = np.linspace(0, 2, 2 * fre_samp, endpoint = False )
a = np.sin(fre * 2 * np.pi * t)
figure, axis = plt.subplots()
axis.plot(t, a)
axis.set_xlabel ('Time (s)')
axis.set_ylabel ('Signal amplitude')
plt.show()
mhmeducations.com
#pass values to det(), Inverse(), Eigen
Vaule and Vector function
import scipy
from scipy import linalg
import numpy as np
#define square matrix
two_d_array = np.array([ [4,5], [3,2] ])
#pass values to det(), Inverse(), Eigen Vaule and Vector function
deter= linalg.det( two_d_array )
inv= scipy.linalg.inv(two_d_array)
eg_val, eg_vect = linalg.eig(two_d_array)

mhmeducations.com
#single integration with a = 0 & b = 1
import scipy
from scipy import integrate
# take f(x) function as f
f = lambda x : x**2
#single integration with a = 0 & b = 1
integration = integrate.quad(f, 0 , 1)
print(integration)
mhmeducations.com
Pandas
pandas is a data analysis and manipulation
library for Python and offer labeled data
structures and statistical functions.

mhmeducations.com
import pandas as pd
XYZ_web= {'Day':[1,2,3,4,5,6],
"Visitors":[1000, 700,6000,1000,400,350],
"Bounce_Rate":[20,20, 23,15,10,34]}
df= pd.DataFrame(XYZ_web)
print(df)

mhmeducations.com
import pandas as pd
df1= pd.DataFrame({ "HPI":[80,90,70,60],"Int_Rate":[2,1,2,3],
"IND_GDP":[50,45,45,67]}, index=[2001, 2002,2003,2004])

df2=pd.DataFrame({ "HPI":[80,90,70,60],"Int_Rate":[2,1,2,3],
"IND_GDP":[50,45,45,67]}, index=[2005, 2006,2007,2008])

merged= pd.merge(df1,df2)

print(merged)
mhmeducations.com
import pandas as pd
df1 = pd.DataFrame({"Int_Rate":[2,1,2,3],
"IND_GDP":[50,45,45,67]}, index=[2001,
2002,2003,2004])

df2= pd.DataFrame({"Low_Tier_HPI":[50,45,67,34],
"Unemployment":[1,3,5,6]}, index=[2001,
2003,2004,2004])

joined= df1.join(df2)
print(joined)
mhmeducations.com
import pandas as pd
df= pd.DataFrame({"Day":[1,2,3,4], "Visitors":[200,
100,230,300],"Bounce_Rate":[20,45,60,10]})
df.set_index("Bounce_Rate", inplace= True)
print(df)

mhmeducations.com
import pandas as pd
df = pd.DataFrame({"Day":[1,2,3,4],
"Visitors":[200, 100,230,300],
"Bounce_Rate":[20,45,60,10]})
print(df)
df = df.rename(columns={"Visitors":"Users"})
print(df)

mhmeducations.com
Matplotlib
It is a 2D plotting library for Python- it produces
publication-quality figures in different hardcopy
formats.

mhmeducations.com
from matplotlib import pyplot as plt

plt.plot([1,2,3],[4,5,1])
plt.show()

mhmeducations.com
from matplotlib import pyplot as plt

x = [5,2,7]
y = [2,16,4]
plt.plot(x,y)
plt.title('Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
mhmeducations.com
from matplotlib import pyplot as plt

plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",width=.5)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Audi", color='r',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show() mhmeducations.com
import matplotlib.pyplot as plt
x = [1,1.5,2,2.5,3,3.5,3.6]
y = [7.5,8,8.5,9,9.5,10,10.5]

x1=[8,8.5,9,9.5,10,10.5,11]
y1=[3,3.5,3.7,4,4.5,5,5.2]

plt.scatter(x,y, label='high income low saving',color='r')


plt.scatter(x1,y1,label='low income high savings',color='b')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()
mhmeducations.com
All the Best

mhmeducations.com

S-ar putea să vă placă și