You are on page 1of 41

Python : Introduction

 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

Python Vs Other Languages :


Easy to read and understand
No compulsion of ; to end command
Identations are mandatory
# Download Python SDK
1. Download link : https://www.python.org/downloads/

# Install Python SDK

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 ;

Test Python environment setup using following steps :


Steps :
1. Open command prompt by typing cmd in run
2. Run following command
Python - - version
3. It results , python version

# Run python programs using command line


Steps :
1. Click start & search – python
2. Click on python 3.x app

# Download & Installtion steps Jupyter in python


Steps :
1. Install Jupyter with standard Python SDK
2. Open cmd , run following command for python 3.x
python3 -m pip install jupyter
for python prior to 3.x
python -m pip install jupyter

# How to run Jupyter

1. Open cmd, run following command


jupyter notebook

# How to execute python using command prompt

Steps:
1. Create python program file with .py extension
2. Open command prompt run following command
cd <program directory>

Ex. If python program are stored in C:\Users\421209\Documents\Python , command will be

3. Run following command to execute python program


Python <file name>.py

Ex: To execute “sample_1.py” , following command is run in command prompt

# Python Beginner reference Links :

Refer link :https://docs.python.org/3/tutorial/


Or
Open following path in windows explorer :
C:\Users\<user account>\AppData\Local\Programs\Python\Python38-32\Doc

# 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 !”)

2. input() : Accepts input from command line interface

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

Rules for declaring variables:


Variable name should not contain space or –
Variable not should start with number or number as name
Variable name should always start with alphabets or “_”

Ex:
a b=12 #wrong
1=5 #wrong
a-b =5 #wrong
a*b = 18 # wrong
a_b=20 #right

How print variables ?


x=10
y=20
print(x,y)

Note : class <str> and class <int> is not allowed as data types are different , concatenation allowed in same datatype

print(‘10’+10) # not allowed

print(int(‘10’)+10) # allowed output :10

print(10+10) # allowed output:10

Local vs Global scope:

Local Scope : scope of variable is local where it is declared in a block


Global Scope : scope of variable is global in program space

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

Text / string type - > 'A' or "A"


numeric types -> int , float , complex
Ex.

int -> 5 , -5
float > 3.24, 1.2 (precision)
complex > 4+6i -> 6i = complex

Sequence type -> list ,tuple , range()

Ex :

ls = ['s',1,2,3] =>ls[0]-> 's'

Mapping type

d ={'name':'nitesh','place':'Mumbai'}

d['name'] #nitesh

set type -> set , frozenset

Set

s= {'1','2',5,6,7,9,10}

frozenset

frozenset({'1','2',5,6,7,9,10})

bool type - True , False

Binary types -> bytes , bytearray , memoryview

0 -> 0000
1 -> 0001
type() -> returns the type of data

print(type(10))

# Type casting - convert one data type into another data type

int- >str = str()

Ex, print(str(10),type(str(10)))

str -> int = int()

Ex, print(int(‘10’),type(int(‘10’)))

float -> str =str()

Ex, print(str(10.34),type(str(10.34)))

str -> float = float()

Ex, print(float(‘10.34’),type(float(‘10.34’)))

int -> float= float()

Ex, print(float(10),type(float(10)))

float -> int = int()

Ex, print(int(10.34),type(int(10.34)))

bool > str = str()

Ex, print(str(True),type(str(True)))

str -> bool =bool()

Ex, print(bool(‘True’),type(bool(‘True’)))

Data type : String


String is collection of characters enclosed in single quote (‘) or double quote(“)

x ='nitesh'
print(x)

y='chavan'
print(x+" "+y)

for i in y:
print(i)

multiline string -> enclosed the collection of statements """ or '''

y='''
This is comment
1
2
3
'''
print(y)

for i in y:
print(i)

len() -> length of string/literal

print(len(y))

for i in range(len(y)):
print(y[i])

Access string element using indexes :

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()

lstrip ()-> removes the white space character from begining


" India is my country ".lstrip()

rstrip ()-> removes the white space character end of string


" India is my country ".rstrip()

lower() : converts string into lover case

upper() : converts string into upper case

replace(old,new) : it replaces old text with new text

split() : i
Search substring using in and not in operator

x = 'banana' in "apple,banana,cherry"

y = 'banana' not in "apple,banana,cherry"

Concatenation (+)
print("Nitesh"+ " "+"Chavan")

format : it formats the pre-formatted / template of string

format() can be used in following ways:


format with no args in {}
'{} & {} are states of india'.format('jammu','kashmir')

format with numeric index in {}


'{0} & {1} are brother'.format('Ram','Shyam')

format with keys in {}

capitalize() >Converts the first character to upper case


"this is simple statement".capitalize()

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() >

encode() > Returns an encoded version of the string

Operators : special symbols which operates on operands to get output


Arithmetic
+
-
/
*
%
**
//
Assingment Operators
=
+=
-=
*=
/=
**=
//=
>>
<<
^=

Logical operators
and
or
not

Comparison / relational operator


==
!=
>
>=
<
<=

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

Type 3 : if .. elif.. 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

num=int(input ("Enter any number : "))

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')

# Check number whether it is odd or even

num=int(input ("Enter any number : "))

if(num ==0):
print("neither odd nor even ");
else:
if( num % 2 == 0):
print(num, ' is even')
else:
print(num,' is odd')

# check whether year is leap or nonleap year

year=int(input ("Enter any year : "))


# logic - if yr is divisible 4 => leap year

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

score=int(input("Enter score : "))

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

Python support following looping statements


1. while
2. for

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>

For ex, print 1 to 10 numbers


I=1

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

# print table of 2 in “Ascending order”

i=1
while i<=10:
Print(i*2)
i+=1

Another methods, for above example


# example 2
j=1
while j<=20:
if j%2==0:
print(j)
j+=1
# example 3
K=2
While k<=20:
print(k)
k=k+2

#break statement : break statements can only be used in looping statement , it stops the execution of loop & control passes
outside of loop

#program to stop if iteration reaches to 10


i=1
while i<=20:

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

# program to skip first 5 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:

for <varirble> in <collections>:


commands..

Following example shows how to traverse through all the elements of collection object using identity membership operator

for i in “I love my country”:


print(i)

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)

Nested loops : loop within in loop

for example :

ls =[1,2,3,4]
ks=[‘A’,’B’,’C’]

for i in ls:
for k in in ks:
print(“{}:{}”.format(i,k))

How to create a table matrix with 5 * 5 size

for i in range (5):


print()
for k in range(5):
print(“*”,end=”\t”)

Create pyramid with max base of 5 elements

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.

function definition -> define the body function


function call -> call the function for execution

def <name>():
#commands
#commands
#commands

#function call
<name>()
function without parameter
def message():
print("hello Abhilash!")

# addition program using function without parameters

# multiplication program using function without parameter

function with parameter :


Parameters are passed in function definition
Arguments are passed during function call

def call(x):
print("hello {}".format(x))

call("Nitesh")
call("Abhilash")

function with default parameter


*rule = keep default parameter list at the end
Use of “return” keyword : return gives capability to function to return value in calling function

The value which is returned by called function can be used in by storing value in variable.

#Recursion : calling of a function again and again until conditions fulfills

def recursive(n):
if(n>0):
ans= n+recursive(n-1)

else:
ans=0

return ans

result=recursive(5)
print(result)

#anonymous inline function : lamda -> anonymous inline function

x = lambda : print("hey Anusha!")

print(x) # reference address for anonym function


print(x())

y= lambda a,b,c : a+b+c

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

# List : O(ordered)C(Changeable)D(Duplication allowed)

lst1= [1,2,3,4]
lst2=list([1,2,3,4])

Access list elements


for i in lst1:
print(i)

Access elements using index & range

lst1[0] #1

lst2[1]=100 # [1,100,3,4]

using range
lst1[0:] #[1,2,3,4]

copy list type to another list using assignment operator


lst3= lst2

append():Adds an element at the end of the list


lst1.add(11)

clear():Removes all the elements from the list


lst2.clear()

copy():Returns a copy of the list


ls2=lst1.copy()

count():Returns the number of elements with the specified value


lst3.count(2)

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’)

pop():Removes the element at the specified position


lst2.pop(2)

remove():Removes the item with the specified value


lst1.remove(100)

reverse():Reverses the order of the list


lst2.reverse()

sort():Sorts the list


lst1.sort()

# Tuple : O(ordered)UC(UnChangeable)D(Duplication allowed)

tp1= (1,2,3,4)
tp2=tuple(tp1)

Access list elements


for i in tp1:
print(i)

Access elements using index & range

tp1[0] #1

tp2[1]=100 # (1,100,3,4)

using range
tp1[0:] #(1,2,3,4)

count() Returns the number of times a specified value occurs in a tuple

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)

access elements of sets using loop


for i in st:
print(i)

add():Adds an element to the set


fruits = {"apple", "banana", "cherry"}
fruits.add("orange")

print(fruits)

clear():Removes all the elements from the set


fruits = {"apple", "banana", "cherry"}

fruits.clear()

print(fruits)

copy():Returns a copy of the set

fruits = {"apple", "banana", "cherry"}

x = fruits.copy()

print(x)

difference():Returns a set containing the difference between two or more sets

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

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)

discard():Remove the specified item

fruits = {"apple", "banana", "cherry"}

fruits.discard("banana")

print(fruits)

intersection():Returns a set, that is the intersection of two other sets

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.intersection(y)
print(z)

intersection_update():Removes the items in this set that are not present in other, specified set(s)

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

isdisjoint():Returns whether two sets have a intersection or not

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "facebook"}

z = x.isdisjoint(y)

print(z)

issubset():Returns whether another set contains this set or not


x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}

z = x.issubset(y)

print(z)

issuperset():Returns whether this set contains another set or not


x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}

z = x.issuperset(y)

print(z)

pop():Removes an element from the set


fruits = {"apple", "banana", "cherry"}

fruits.pop()

print(fruits)

remove():Removes the specified element

fruits = {"apple", "banana", "cherry"}

fruits.remove("banana")

print(fruits)

symmetric_difference():Returns a set with the symmetric differences of two sets


x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)

print(z)

symmetric_difference_update():inserts the symmetric differences from this set and another


x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

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 = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.update(y)

print(x)

#Dictionary : UO(Unordered)C(Changeable)UD(unduplicated)

dc1= {"name":"nitesh","age":31}
dc2=dict(dc1)

Access dict. elements


for i in dc1:
print(i)

for i,j in dc1.items():


print(i,j)

for j in dc1.keys():
print(j)

for k in dc2.values():
print(k)

Access elements using index & range

dc1["name"] #nitesh

dc2["name"]="Ankit" # {"name":"nitesh","age":31}

Duplication is not allowed


dc1={"name":"nitesh","age":31,"name":"amey"} # not allowed
clear():Removes all the elements from the dictionary
dc1.clear()

copy():Returns a copy of the dictionary


dc2=dc1.copy()

fromkeys():Returns a dictionary with the specified keys and value


x = ('key1', 'key2', 'key3')
y=0

thisdict = dict.fromkeys(x, y)

print(thisdict)

get():Returns the value of the specified key


dc1.get(“name”)

items():Returns a list containing a tuple for each key value pair


for i,j in dc1.items():
print(i,j)

keys():Returns a list containing the dictionary's keys


for j in dc1.keys():
print(j)

pop():Removes the element with the specified key


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop("model")

print(car)

popitem():Removes the last inserted key-value pair


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

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)

update():Updates the dictionary with the specified key-value pairs


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop("model")

print(car)

values():Returns a list of all the values in the dictionary


for k in dc2.values():
print(k)

File Handling :

print(dir())

open(filename,mode+filetype) -> opens the file

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

f = open("New Text Document.txt","r")


read() - > reads the content from file

content = f.read()
print(content)

print(f.read())

print(f.read(5))

readline() -> reads content by line

print(f.readline())
print(f.readline())
read content line by line
for i in f:
print(i)

f.close() close the connection

close() -> closes the file

write() -> writes the content to the file

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()

writelines() - > writes content line by line

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))

#remove the file from filesystem


os.remove("nitesh.png")

#exists(filename) - test the existence of file

'''if os.path.exists("abhilash1.txt"):
print("yes, it is there!")
else:
print("Not available !")'''

#rmdir() – remove directory from file system


os.rmdir("bck")
os.mkdir("24122020")

#listdir() – lists out directory content of file system


ls=a.listdir("C:\\Users\\421209\\Documents\\Python\\Abhilash")
print(ls)

#write content from one file to another file


f =open("0.jpg","rb")
#print(f.read())
content=f.read()
f.close()

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()

#program to copy file from one directory to another directory


import os
import shutil

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)

JSON : storing and exchanging data

import json # loads JSON Module in python program

st ='{"name":"nitesh","place":"mumbai"}' # string formatted json variable

print(st,type(st))

obj = json.loads(st) #converts json formatted string to python object(dictonary)

print(obj,type(obj))

jobj =json.dumps(obj) #converts python object(dictionary) to json formatted string

print(jobj,type(jobj))
Module : Its python code library or package which avails to reuse python code & organises the python code

Modules can be imported in 2 ways :


1. Import <module name>
2. Form <module name> import <[members,..]>

Using import <module name>

Print(dir()) #list out all loaded modules in python program

print(dir(__file__)) # list out all members of __file__ module

# Loop to list all loaded modules in python program


for i in dir():
print(i)

#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)

#Create module – add.py


def plus(x,y):
return x+y

x= lambda m,n:m+n

def message():
print("Hello !")

# Import add module in moduleex.py program


Source code of moduleex.py

import add

print(dir())

for i in dir(add):
print(i)

print(add.plus(10,20))
print(add.x(200,300))

#alias module using ‘as’ keyword

import add as a

print(a.plus(100,200)) # access module using alias ‘a’


print(a.x(300,400)) # access module using alias ‘a’
Using from <module name> import <members..>

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())

Object Oriented Programming (OOP)

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 with class methods

class A:
j=0 # class variable
def display(): # class method
A.j=A.j+1
print(A.j)

def show(self) : #object method


A.display()

Obj = A()
Obj.show() #1
Obj.show() #2
Obj1=A()
Obj1.show() #3
Obj1.show() #4

Class methods share same copy of methods among all objects ,

#class with object method


class A:
def __init__(self):
self.i=0

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

Object method always carries individual copy object methods.

__init__() : Specialised method to initialise member of classes and gets called whenever instance of an object is created.

#Program to set and get value of class member

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()

#calculator program using class


class Calculator:

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()

opt = input("Do you want to continue (y/n) :")


#print(opt)
if (opt.upper()!='Y'):
print("Bye !")
break;

Database Handling :

Database management system(DBMS) - Role : organises & manages content & access controls for all data objects in database
system

SQL - Structred Query Language - SQL programming

CRUD Operations - CREATE, READ, INSERT, UPDATE, DELETE

DATABASES Ojects: TABLES, VIEWS, TRIGGER, PROCEDURES

DDL - Data definition language


CREATE DATABASE

Syntax: CREATE DATABASE <database-name>

create database besant;

CREATE TABLE

DML - Data Manipulation language


INSERT INTO
UPDATE
DELETE

DCL - Data Control language


GRANT
REVOKE

SQL Examples of DDL & DML Statements

# create new database


CREATE DATABASE Besant;

# show list of databases


show databases;

# select database to perform operation


use besant;

# create new table in selected database


CREATE TABLE Student (name varchar(10),age int);
# show list of tables in existing database
show tables;

# select all records from table


select * from student;

# insert record in table


INSERT INTO Student values('Nitesh',31)

# update record in table


UPDATE Student SET age =32 where name='Nitesh';

# delete record from table


Delete from Student where name='Nitesh';

Python – Database Handling Programs (Basic)

#Program : Create a Database

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()

#Program : Show all databases in DBMS

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()

#Program : Create a table in database

import mysql.connector as ms

con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()

cmd=”Create table Student (name varchar(10,age int)”

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()

#Program : Insert a record in table

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()

#Program : Update a record in table

import mysql.connector as ms

con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)
cur=con.cursor()

cmd=”UPDATE STUDENT SET AGE=31 WHERE name= ‘nitesh’”


cur.execute(cmd)

con.commit()

con.close()

#Program : Delete a record in table

import mysql.connector as ms

con =ms.connect(host=”localhost”,port=3306,user=””,password=””,database=”BESANT”)

cur=con.cursor()

cmd=”DELETE FROM STUDENT WHERE name= ‘nitesh’”


cur.execute(cmd)

con.commit()

con.close()
Python – Database Handling Programs (Advanced)

# Program : show one records from table

import mysql.connector as ms

con = ms.connect(host="",user="",password="",database="")

cur= con.cursor()

cmd="Select * from Employee"

cur.execute(cmd)

res = cur.fetchone()

for i in res:
print(i)

con.close()

# Program : show one records from table

import mysql.connector as ms

con = ms.connect(host="",user="",password="",database="")

cur= con.cursor()

cmd="Select * from Employee"

cur.execute(cmd)

res = cur.fetchall()

for i in res:
print(i)

con.close()

# Programe : Update records in table

import mysql.connector as ms

con = ms.connect(host="",user="",password="",database="")

cur= con.cursor()

cmd="Update Employees set salary=%s where name=%s"

tp = (22000,'Amit')
cur.execute(cmd,tp)

con.commit()

con.close()

# Program : Update multiple records in table

import mysql.connector as ms

con = ms.connect(host="",user="",password="",database="")

cur= con.cursor()

cmd="Update Employees set salary=%s where name=%s"

tps = [(22000,'Amit'),(50000,'Pornima'),(10000,'Nitesh')]

cur.executemany(cmd,tps)

con.commit()

con.close()

# Program : insert a records in table

import mysql.connector as ms

con = ms.connect(host="',user="",password="",database="")

cur = con.cursor()

cmd = "INSERT INTO STUDENT VALUES(%s,%s)"


tp =('Nitesh',31)

cur.execute(cmd,tp)

con.commit()

con.close()

# Program : Insert many records in a table

import mysql.connector as ms

con = ms.connect(host="",user="",password="",database="")

cur= con.cursor()

cmd="INSERT INTO Employees Values(%s,%s,%s)"

tps = [('Amit',23,13000),('Sakshi',28,15000),('Pornima',24,15000)]
cur.executemany(cmd,tps)

con.commit()

con.close()

# Database : Moduler program

import mysql.connector as ms

class Database :

def __init__(this):
con =ms.connect(host='localhost',port=3306,user="",password="",database="")
cur = con.cursor()

class ScroeCard (Database):

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

# Exception Handling in Python

# Error : an event which hals the execution of program.


# Exception: way of bypassing error and it allows to excute complete program by alerting messages

#try : test the error


#except : handle the error displays context of error
#finally : allows command execution
"""
try:
print("1"+"nitesh") # will check block of code

except NameError:
print("Name error is identified")
except:
print("Concatination is not possible")
else:
print("i am executing because ,exception is thrown")

#Inline Exceptions:

x = int(input("enter any value : "))

if x<0: # checks the conditional


raise Exception("x should be +ve integer")
else:
print(x)

# Iterators :

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

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

obj = iter(ls) # list -iterable object

print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))

for i in obj:
print(i)

# Iterator Object in Class :

__iter__() :initialization of member and it returns object


__next__() :moves pointer to next possible record

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: allows to return muliple values via . generator function.

#Generator Object : Generator functions return a generator object. Generator objects are used either by calling the next
method on the generator object

def getNumber(n): # Generator function


yield n+1;
yield n+2;
yield n+3;

# Generator object will be created with reference generator function

obj = iter(getNumber(1)) #Generator object


print(next(obj))
print(next(obj))
print(next(obj))

# GUI Module : Tkinter


It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way
to create the GUI applications

Tkinter
|
container
|
Frame
|
widget (Label,Entry,Button,Radiobutton,Checkbutton...)

#how to import tkinter

1. import tkinter
2. from tkinter import *

# Program : Create root container

from tkinter import *


w = Tk() # Tk class creates container window object
w.title("General window") # title(“XXXX”) – sets the title to window
w.geometry('500x250') # geometry() – sets height & width for window object

lbl = Label(w,text ="Good Evening",fg='red',bg='yellow') # Label class – to create label widget

lbl.pack(side=LEFT) #pack() sets the layout for widget

w.mainloop() # execution start point

You might also like