Python Guide - v14
Python Guide - v14
Programing language
Guido van Rossum, and released in 1991.
Use : Standalone , web apps , system & statistical app development
Run on cross platforms window, mac , rasberry pi & linux etc
Capabilites :
o GUI app development
o Web application development
o Big data & relational data handing capabilities
o Rapid development
Easy to learn & understand , native language similarity (English)
Less writeups for code
Executes as soon as run adding quick prototyping using iterpreter system
Make use of functional , procedural & Object oriented approach
IDE Support availale for Pycharm , netbeans , eclipse , thonny
Execute downloaded setup in default location on c:\ drive or set custom path
# Configure Python
OR
Modify system path variable : PATH
C:\Users\<user account>\AppData\Local\Programs\Python\Python38-32
C:\Users\<user account>\AppData\Local\Programs\Python\Python38-32\Lib ;
C:\Users\<user account>\AppData\Local\Programs\Python\Python38-32\libs ;
C:\Users\<user account>\AppData\Local\Programs\Python\Python38-32\Scripts ;
Steps:
1. Create python program file with .py extension
2. Open command prompt run following command
cd <program directory>
# Python Basics :
Syntax :
Comments : Improves readability & illustates the logic description
o Single line : ‘#’ at the beginning of command to interpret it as comment
Ex :
# single line comment will not execute & display in console
o Multiline
Ex :
‘’’
Multiline comments starts with 3 quotation marks at the beginning
& ends with 3 quotation marks as end of comments
‘’’
General input & output functions
1. print() : Displays output on command line
Ex :
print (“Hello world !”)
Ex :
input(“Enter any value : ”)
# Variables
Variables are containers to store data values , it creates memory block in system to store different types of data values.
For Ex. y = 1
Ex:
a b=12 #wrong
1=5 #wrong
a-b =5 #wrong
a*b = 18 # wrong
a_b=20 #right
Note : class <str> and class <int> is not allowed as data types are different , concatenation allowed in same datatype
Ex:
a =10
def show():
a=20
print(a)
show()
output : 20
To access global value in local scope use “global” keyword
a =10
def show():
global a
print(a)
show()
output : 10
Local vs Global
Local variable : is available in local scope , can not be accessible or change outside local scope
Global variable : is available to global scope , can be accessible & changed explicitly in local scope using “global” keyword
# Data Types
int -> 5 , -5
float > 3.24, 1.2 (precision)
complex > 4+6i -> 6i = complex
Ex :
Mapping type
d ={'name':'nitesh','place':'Mumbai'}
d['name'] #nitesh
Set
s= {'1','2',5,6,7,9,10}
frozenset
frozenset({'1','2',5,6,7,9,10})
0 -> 0000
1 -> 0001
type() -> returns the type of data
print(type(10))
# Type casting - convert one data type into another data type
Ex, print(str(10),type(str(10)))
Ex, print(int(‘10’),type(int(‘10’)))
Ex, print(str(10.34),type(str(10.34)))
Ex, print(float(‘10.34’),type(float(‘10.34’)))
Ex, print(float(10),type(float(10)))
Ex, print(int(10.34),type(int(10.34)))
Ex, print(str(True),type(str(True)))
Ex, print(bool(‘True’),type(bool(‘True’)))
x ='nitesh'
print(x)
y='chavan'
print(x+" "+y)
for i in y:
print(i)
y='''
This is comment
1
2
3
'''
print(y)
for i in y:
print(i)
print(len(y))
for i in range(len(y)):
print(y[i])
print(y[0]) #c
print(y[0:]) # all elements
print(y[1:3]) # start witn index 1 and it will end at index 2
print(y[-1])
print(y[:-1]) # all elements except last element
y='chavan'
strip ()-> removes the white space character from begining and end of string
" India is my country ".strip()
split() : i
Search substring using in and not in operator
x = 'banana' in "apple,banana,cherry"
Concatenation (+)
print("Nitesh"+ " "+"Chavan")
index() > Searches the string for a specified value and returns the position of where it was found
find() > Searches the string for a specified value and returns the position of where it was found casefold() > lower format of text
swapcase() > Swaps cases, lower case becomes upper case and vice versa
isdecimal > returns unicode formatted decimal value with True / False
"\u0033".isdecimal()
isnumeric() > Returns True if all characters in the string are numeric
'0120210'.isnumeric()
isalpha() > Returns True if all characters in the string are in the alphabet
isdigit() > Returns True if all characters in the string are digits
‘56’.isdigit()
isupper() > Returns True if all characters in the string are upper case
‘INDIA’.isupper()
islower() > Returns True if all characters in the string are lower case
join() > Joins the elements of an iterable to the end of the string
tp=(‘apple’,’banana’,’orange’)
“;”.join(tp)
zfill() > Fills the string with a specified number of 0 values at the beginning
‘500’.zfill(5)
isspace() > Returns True if all characters in the string are whitespaces
isprintable() >
Logical operators
and
or
not
identity operator
is
is not
Membership operator
in
not in
Bitwise operator
#Conditional Statement : ‘If’ statements are conditional statement , based on condition it evaluates results.
Types of IF statement
if – Only single condition is allowed & condition is True it executes command from IF block
if else - Only single condition is allowed & condition is True it executes command from IF block, if condition evaluates False it
executes command from else block
if elif else – series of if conditions are prioritise based on condition evaluation if none of the condition executes True it executes
commands from Else block
nested if : If within if / else block , based on condition evaluation it executes the result.
Type 1:
if 5==6:
print("yes ")
if 5==5:
print(‘Yes’)
Type 2 : if .. else
x=5
If x<0:
print(‘x<0’)
elif x>=0 and x<=3:
print(‘0 <x<3’):
else:
print(‘x>3’)
Type 4 : nested if
if within if or if within else block
n=25
if n<0:
print('negative')
if (n<-5):
print('value is less than -5')
else:
print('positive')
if (n>5):
print('value is greater than 5)
# Check number whether it is odd or even
if(num ==0):
print("neither odd nor even ");
else:
if( num % 2 == 0):
print(num, ' is even'):
else:
print(num,' is odd')
n=10
if n<0:
print('negative')
if (n<-5):
print('value is less than -5')
else:
print('positive')
if (n<5):
print('value is less than 5')
else:
print('value is greater than 5')
if(num ==0):
print("neither odd nor even ");
else:
if( num % 2 == 0):
print(num, ' is even')
else:
print(num,' is odd')
if ( year % 4==0):
print('leap year')
else:
print('non leap year')
# Score card using if statement score>90 - > A , 60<score<90 -> B , 45<score<60 ->C ,<45->D
if score >=90:
print('A')
elif score >=60 and score <90 :
print('B')
elif score >=45 and score <60 :
print('C')
else:
print('D')
loops : loops statement helps to iterate the commands until condition matches
While : While statement initializes the counter variable a & uses same counter for stepping in looping until it satisfies the
condition
Syntax :
<initialize program counter>
While <condition>:
Commands
<increment / decrement of program counte>
While i<=10:
Print(i)
I+=1
Ex, print 1 to 10 number in descending order
j=10
for j>=1:
print(j)
j=j-1
i=1
while i<=10:
Print(i*2)
i+=1
#break statement : break statements can only be used in looping statement , it stops the execution of loop & control passes
outside of loop
if i>=20:
break:
else :
print(10)
i=i+1
#continue statement :continue can only be used in looping statement , it skips the iteration in loop & continues the iteration
i=1
while i<=20:
if i<=5:
i+=1
continue
else:
print(i)
i+=1
For Loop : works exactly same as while loop , It helps to traverse across all elements in collections (tuple,array or string)
Syntax:
Following example shows how to traverse through all the elements of collection object using identity membership operator
for j in [1,3,4,5,6,7]:
print(j)
for k in (23,43,12,34,89,90,):
print(k)
Use of range -> range is another sequential collection of objects , it is possible to traverse through the value using range
for m in range(6):
print(m)
for example :
ls =[1,2,3,4]
ks=[‘A’,’B’,’C’]
for i in ls:
for k in in ks:
print(“{}:{}”.format(i,k))
for i in range(5):
print()
j=1
while j<=i:
print(“*”,end=”\t”)
Functions :
block -> collection of commands , execution will work only if it is being called.
def <name>():
#commands
#commands
#commands
#function call
<name>()
function without parameter
def message():
print("hello Abhilash!")
def call(x):
print("hello {}".format(x))
call("Nitesh")
call("Abhilash")
The value which is returned by called function can be used in by storing value in variable.
def recursive(n):
if(n>0):
ans= n+recursive(n-1)
else:
ans=0
return ans
result=recursive(5)
print(result)
print(y(100,200,300))
#function with arbitrary arguments
def message(*n):
print("argument is : ",n[2])
ls=[10,20,30,40]
name="Anusha"
message(0,ls,name)
#Data Structure
1. List
2. Tuple
3. Set
4. Dictionary
lst1= [1,2,3,4]
lst2=list([1,2,3,4])
lst1[0] #1
lst2[1]=100 # [1,100,3,4]
using range
lst1[0:] #[1,2,3,4]
extend():Add the elements of a list (or any iterable), to the end of the current list
lst2.extend(lst1)
index():Returns the index of the first element with the specified value
lst1.index(1)
insert():Adds an element at the specified position
lst2.insert(1,’S’)
tp1= (1,2,3,4)
tp2=tuple(tp1)
tp1[0] #1
tp2[1]=100 # (1,100,3,4)
using range
tp1[0:] #(1,2,3,4)
tp1.count(2)
index() Searches the tuple for a specified value and returns the position of where it was found
tp2.index(1)
# Set : UO(Unordered)UI(UnIndexed)UD(Unduplicated)
st ={1,2,3,4,6}
st1=set(st)
print(fruits)
fruits.clear()
print(fruits)
x = fruits.copy()
print(x)
z = x.difference(y)
print(z)
difference_update():Removes the items in this set that are also included in another, specified set
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
fruits.discard("banana")
print(fruits)
z = x.intersection(y)
print(z)
intersection_update():Removes the items in this set that are not present in other, specified set(s)
x.intersection_update(y)
print(x)
z = x.isdisjoint(y)
print(z)
z = x.issubset(y)
print(z)
z = x.issuperset(y)
print(z)
fruits.pop()
print(fruits)
fruits.remove("banana")
print(fruits)
print(z)
x.symmetric_difference_update(y)
print(x)
union():Return a set containing the union of sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
update():Update the set with the union of this set and others
x.update(y)
print(x)
#Dictionary : UO(Unordered)C(Changeable)UD(unduplicated)
dc1= {"name":"nitesh","age":31}
dc2=dict(dc1)
for j in dc1.keys():
print(j)
for k in dc2.values():
print(k)
dc1["name"] #nitesh
dc2["name"]="Ankit" # {"name":"nitesh","age":31}
thisdict = dict.fromkeys(x, y)
print(thisdict)
car.pop("model")
print(car)
car.popitem()
print(car)
setdefault():Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
car.pop("model")
print(car)
File Handling :
print(dir())
obj = open("nitesh.png","xb")
print(obj)
mode
x - creating new file
r - reading content
w - writing new content \ overrding existing content with new one
a - appends the content to existing content
file type
t -> text file , default
b -> Binary mode
content = f.read()
print(content)
print(f.read())
print(f.read(5))
print(f.readline())
print(f.readline())
read content line by line
for i in f:
print(i)
f = open("Abhilash.txt","w")
f.write("Good Evening !")
f.close()
f= open("Abhilash.txt","r")
print(f.read())
f.close()
f = open("Abhilash.txt","a")
f.write("How are you doing ?")
f.close()
f= open("Abhilash.txt","r")
print(f.read())
f.close()
f = open("Abhilash.txt","a")
f.writelines("where are you ?")
f.writelines("Are you single?")
f.close()
OS Module in Python
Import os as a
#displays all property & methods of Module os
print( dir(a))
'''if os.path.exists("abhilash1.txt"):
print("yes, it is there!")
else:
print("Not available !")'''
f= open("C:\\Users\\421209\\Documents\\Web1.jpg","xb")
f.close()
f=open("C:\\Users\\421209\\Documents\\Web1.jpg","wb")
f.write(content)
f.close()
src=""
dest=""
if os.path.exists("C:\\Users\\421209\\Documents\\Web"):
src="C:\\Users\\421209\\Documents\\Web"
if os.path.exists("C:\\Users\\421209\\Documents\\Python\\DataScience"):
dest="C:\\Users\\421209\\Documents\\Python\\DataScience"
shutil.copy(src,dest)
print(st,type(st))
print(obj,type(obj))
print(jobj,type(jobj))
Module : Its python code library or package which avails to reuse python code & organises the python code
#Loop to list all loladed modules and members of each module using python program
for i in dir():
print(" ----------------- "+i+" -------------------------")
for j in dir(i):
print(j)
x= lambda m,n:m+n
def message():
print("Hello !")
import add
print(dir())
for i in dir(add):
print(i)
print(add.plus(10,20))
print(add.x(200,300))
import add as a
from add import plus,message # it avails to import only required members in python program
print(plus(100,200)) # access the member direct i.e without specifying module name
print(message())
Class – template / blueprint which defines the structure , structure contains members of class. Properties & methods are
members of class.
Object – is an instance of class and always associated with cost , it will be created whenever special constructor (__init__()) of
object is getting called during object invocation. As an object is an instance of class - > all objects can access properties and
methods with reference to an object .
Class methods / properties – can be accessible with the help of class reference , All objects shares same copy of class method
Object methods / properties – can be accessible with the help of object reference , all objects share individual copy of each
Class Syntax :
class <class-name>:
#members of class
Object Declaration:
<obj name> = <class name>()
# class example :
class A:
pass;
obj = A()
class A:
j=0 # class variable
def display(): # class method
A.j=A.j+1
print(A.j)
Obj = A()
Obj.show() #1
Obj.show() #2
Obj1=A()
Obj1.show() #3
Obj1.show() #4
def display(self):
self.i=self.i+1
print(self.i)
Obj1=A()
Obj1.show() #1
Obj1.show() #2
Obj2=A()
Obj2.show() #1
Obj2.show() #2
__init__() : Specialised method to initialise member of classes and gets called whenever instance of an object is created.
class Human:
def __init__(self):
self.height=1.0
def setHeight(self,x):
self.height=x;
print("Your height is : ", self.height)
abhilash = Human()
abhilash.setHeight(5.11)
nitesh = Human()
nitesh.setHeight(6.0)
#program to set members of class using __init__() method
class vehicle:
def __init__(self,wheels,headlights,type):
self.wheels=wheels
self.headlights=headlights
self.type=type
def demo(self):
print(" Wheels : ",self.wheels);
print(" Headlights : ",self.headlights);
print(" Type : ",self.type);
car = vehicle(4,2,'sedan')
car.demo()
cycle=vehicle(2,0,'light')
cycle.demo()
truck=vehicle(6,4,'heavy')
truck.demo()
def __init__(self,x,y):
self.x=x
self.y=y
def add(self):
return self.x+self.y
def sub(self):
return self.x-self.y
def div(self):
return self.x/self.y
def mul(self):
return self.x*self.y
def compute(self):
print("Addition: ",self.add())
print("Subtraction: ",self.sub())
print("Division: ",self.div())
print("Multiplication: ",self.mul())
while True:
x = int(input("Enter x : "))
y = int(input("Enter y : "))
obj = Calculator(x,y)
print(" ---- Output ----")
obj.compute()
Database Handling :
Database management system(DBMS) - Role : organises & manages content & access controls for all data objects in database
system
CREATE TABLE
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””)
cur=con.cursor()
cmd=”Create Database BESANT”
cur.execute(cmd)
con.close()
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””)
cur=con.cursor()
cmd=”Show Databases”
cur.execute(cmd)
for i in cur:
print(i)
con.close()
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()
cur.execute(cmd)
con.close()
#Program : Show all tables in database
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()
cmd=”Show tables”
cur.execute(cmd)
for i in cur:
print(i)
con.close()
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()
cmd=”INSERT INTO STUDENT VALUES(‘nitesh’,31)”
cur.execute(cmd)
con.commit()
con.close()
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()
con.commit()
con.close()
import mysql.connector as ms
con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()
con.commit()
con.close()
Python – Database Handling Programs (Advanced)
import mysql.connector as ms
con = ms.connect(host="",user="",password="",database="")
cur= con.cursor()
cur.execute(cmd)
res = cur.fetchone()
for i in res:
print(i)
con.close()
import mysql.connector as ms
con = ms.connect(host="",user="",password="",database="")
cur= con.cursor()
cur.execute(cmd)
res = cur.fetchall()
for i in res:
print(i)
con.close()
import mysql.connector as ms
con = ms.connect(host="",user="",password="",database="")
cur= con.cursor()
tp = (22000,'Amit')
cur.execute(cmd,tp)
con.commit()
con.close()
import mysql.connector as ms
con = ms.connect(host="",user="",password="",database="")
cur= con.cursor()
tps = [(22000,'Amit'),(50000,'Pornima'),(10000,'Nitesh')]
cur.executemany(cmd,tps)
con.commit()
con.close()
import mysql.connector as ms
con = ms.connect(host="',user="",password="",database="")
cur = con.cursor()
cur.execute(cmd,tp)
con.commit()
con.close()
import mysql.connector as ms
con = ms.connect(host="",user="",password="",database="")
cur= con.cursor()
tps = [('Amit',23,13000),('Sakshi',28,15000),('Pornima',24,15000)]
cur.executemany(cmd,tps)
con.commit()
con.close()
import mysql.connector as ms
class Database :
def __init__(this):
con =ms.connect(host='localhost',port=3306,user="",password="",database="")
cur = con.cursor()
def __init__(this,name,score):
this.name=name
this.score=score
Database.__init__(this)
def addRecord(this):
cmd = "INSERT INTO STUDENT VALUES(%s,%s)"
t=(this.name,this.score)
cur=this.cur
cur.execute(cmd,t)
con=this.con
con.commit()
#con.close()
def showRecord(this):
cmd = "SELECT * from STUDENT"
cur=this.cur
cur.execute(cmd)
res = cur.fetchall()
for i in res:
print(i)
con=this.con
#con.close()
while True:
i = int(input("Enter your option : 1. Add Records 2.Show Records"))
if i==1:
name = input("Enter name : ")
score = input("Score : ")
obj = ScoreCard(name,score)
obj.addRecord()
elif i==2:
obj = ScoreCard("","")
obj.showRecords()
else:
obj = ScoreCard("","")
con=(this.con)
con.close()
break
except NameError:
print("Name error is identified")
except:
print("Concatination is not possible")
else:
print("i am executing because ,exception is thrown")
#Inline Exceptions:
# Iterators :
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
print(next(myit))
print(next(myit))
print(next(myit))
# iter() - > returns iterable object
# next() -> points to next possible value of collection
ls = [1,2,3,5] # primitive-iterable
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
for i in obj:
print(i)
class A:
def __iter__(this):
this.a=1;
return this;
def __next__(this):
#print(this.a)
this.a= this.a+1
return this.a;
obj = A()
it = iter(obj)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
#Generator Object : Generator functions return a generator object. Generator objects are used either by calling the next
method on the generator object
Tkinter
|
container
|
Frame
|
widget (Label,Entry,Button,Radiobutton,Checkbutton...)
1. import tkinter
2. from tkinter import *