Python Class and Object

Python is a object-oriented programming Language, which is used to implement all OOP concept at the programming level.

Python class is a

  1. Template or a Blue Print
  2. Contains Variables, Methods and Constructors
  3. Variable shows the object Properties and Methods shows Actions performed by the object.

Syntax:
class <classname>:
// class members

Example: 1
# class and objects in python

#class declaration
class Emp:
# method
def assign(self):
self.empno=2008
self.ename=’Sanjay’

def showEmpInfo(self):
print (“Employee Details”)
print (“Employee no : “, self.empno)
print(“Employee name : “,self.ename)

#object creation
objE=Emp()
#calling the method using object
objE.assign()
objE.showEmpInfo()

Example: 2

#class declaration
class Emp:
# method declaration
def assign1(self,empno, empname):
self.empno=empno
self.empname=empname

def showEmpInfo(self):
print (“Employee Details”)
print (“Employee no : “, self.empno)
print(“Employee name : “, self.empname)

#object creation
objE1=Emp()
objE2=Emp()

print(“Example self keyword in python class”)
#calling the method using object
objE1.assign1(2009, “Vijaya”)
objE1.showEmpInfo()

objE2.assign1(2004, “Sanjay”)
objE2.showEmpInfo()

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Advertisements

Python Module

Module is a collection of classes and Functions in Python. Functions are grouped into module based on its functionality.

Type

  1. Built-in
  2. User Defined

Example – User Defined Module

# Math Module

def add(a,b):
return a+b

def sub(a,b):
return a-b

def prod(a,b):
return a*b

def div(a,b):
return a/b

Save the file as “mathdemo.py”

Program 1
Using the Module

import mathdemo as md

print(“Difference = “, mathdemo.sub(5,3))
print(“Product = “, md.Div(9,3))

Program 2
# calling the module
from mathdemo import *

print(“Sum = “, add(2,3))
print(“Product = “, prod(2,3))

Note: import keyword is used add the module reference to the current Python file.
prefix the module name before the function name.

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Exception Handling in Python

Exception is a run time error which occurs during the program execution.  Python provides in-built support for handling the runtime error using try-except block.

syntax:

try:
// code which may throw the exception
except:
// exception handler
finally:
// clean up code

try block contains the code which may throw the Exception. except block contains the Exception handler to handle the Exception. finally block code will be executed when the exception is raised or not raised.

Example 1
# Exception Handling
try:
a=int(input(“First Number: “))
b=int(input(“Second Number: “))
c=a/b
print (“Output:”, c)
except Exception:
print(“Number can’t be Divided by 0”)
finally:
print(“There may or may not have been an exception.”)

Note: Exception is built-in class which handles all types of exceptions in Python

Example 2: try with Multiple except block
try:
x = int(input(“Your number: “))
res = 15 / x
print(“Result – “, res)
except ValueError:
print(“You should have given either an character or a float”)
except ZeroDivisionError:
print(“Infinity”)

Note: one except block can handle only one type of exception. to catch more than one type of exception a try block can have multiple except block

Example – 3 try block with else block
try:
a=10/2
print (“Output : “, a)
except ZeroDivisionError:
print(“No. Cann’t be divieded by Zero”)
else:
print(“No Exception”)
Note: else block will be executed whenever there is no exception

Example – 4 try with raise keyword
try:
x=”a”
a=10/x
print (“Output : “, a)
except:
      raise # prints the type of Exception raised by the code

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Python break, continue and pass Statements

break Statement:

  1. used to stop the looping statement before the given condition becomes False.
  2. Used only in the looping statements like while or for.

Example for break:
# break example in python
for i in range(1,10):
if i==6:
break
else:
print(i)
Note: Loop Stops when the i value is 6.

continue Statement:

  1. Used to skip the current iteration
  2. Used only in the looping statements like while or for.

# continue example in python
for i in range(1,11):
if i==6:
continue
else:
print(i)

pass Statement

  1. to Stop and proceed while executing the program

# pass example in python
for i in range(1,10):
if i==6:
pass
print(“pass command”)
print(i)

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Python Complex Datatypes

Python Complex data types

  1. List
  2. Tuple
  3. Dictionary

List

  1. Group of Values belong different data type enclosed in [ ] bracket
  2. Value is called as item or Element
  3. Each Element will be retrieved based on the position.

List Operation

  1. Indexing – Retrieving only one item based on its position
  2. Slicing – Retrieving group of elements sequentially
  3. Repeation – Printing the List specified no. of times.

List Example:
# List creation
empList = [ 2001, ‘Shivani’,2005, ‘Sanjay’, 2007, ‘Babu’]
print (“employee Details : \n”, empList)

#Indexing
print(“2nd Position : “, empList[1])

#Slicing
print(“1st to 4th element : “, empList[0:4])

#printing from 2nd element to last element
print(“2nd to last element : “, empList[1:])

#Repeation
print(empList*2)

Tuple

  1. Elements are Enclosed in the round brackets ()
  2. Read only – Values can’t be modified.
  3. Supports all the List operations.

Example – Tuple
# Tuple creation
empTuple = ( 2001, ‘Shivani’,2005, ‘Sanjay’, 2007, ‘Babu’)
print (“employee Details : \n”, empTuple)

#specific element from Tuple
print(“2nd Position : “, empTuple[1])

#printing Range of element
print(“1st to 4th element : “, empTuple[0:4])

#printing from 3nd element to Tuple element
print(“3rd position to Last : “, empTuple[2:])

#printing the Tuple two times
print(empTuple*2)

Dictionary

  1. Elements are stored in Key-Value Format
  2. Key is unique and value can be duplicated
  3. Value will be Retrieved based on the key value.

Example – Dictionary
# Dictionary Creation
empDList = {}
empDList[1002]=”Sanjay”
empDList[1003]=’Sania’
empDList[1005]=’Sowmya’

print (“employee Details : \n”, empDList)
print(empDList.keys()) # prints all the keys
print(empDList.values()) # prints all the values

Happy Learning
Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

for loop in Python

for loop is a definite loop and works with all types of values like integer, float, string, list in python.
Syntax:
for in :
Statements

Example: for loop with number values
Example 1:
# For Loop – Prints the number from 1 to 10
for num in range(1,11):
print(num)
range() function is used to specify the range of values for integer and float datatype.

Example 2:
# For Loop – Prints the number from 1 to 10 in reverse order
for num in reversed (range(1,11,2)):
print(num)

Example 3:
# For loop with String value
strN=”Win Corporate”

for ch in strN:
print (“Current Letter :” + ch)
#prints one character at a time from starting to the end of the string

Example: 4
# For loop with List
Company = [‘Win’, ‘Corporate’, ‘Training’]
for c in Company:
print (“Current value :” + c)
# prints one item at a time from the list.

Happy Learning
Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Python while loop

Python while Loop
while loop
It works as long as the given condition is true.
Syntax:
while ():
// Statements

Example 1:
# Printing the no.1 to 10
ctr=1 #initialization

print(“While Loop Demo”)
while (ctr<=10): #condition
print (ctr)
ctr = ctr +1 #incrementing part

Example 2:
#Printing the No.s from 1000 to 100

ctr=1000
print(“While Loop Demo”)
while (ctr >=100):
print (ctr)
ctr = ctr – 100
else:
print(“else part will execute when the condition becomes false”)

Note: Else is an optional and will execute when the condition given the while loop fails.

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile