Python Class PRG

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

https://codippa.

com/tutorials/python/

https://www.educative.io/edpresso/how-is-tryexcept-used-in-python

https://realpython.com/regex-python/#quantifiers

https://www.youtube.com/watch?v=vFiBKa4VbtU

https://www.analyticsvidhya.com/blog/2015/06/regular-expression-python/

1.Program to calculate sum

n = 10
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )

2. to find average of elements list

n=int(input("Enter the number of elements to be inserted: "))


a=[]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))

3. calculate sum and average of natural number using formula

n = 10
sum = n * (n+1) / 2
average = ( n * (n+1) / 2) / n
print("Sum of fthe irst ", n, "natural numbers using formula is: ", sum )
print("Average of the first ", n, "natural numbers using formula is: ", average )

4. sum and average

numbers = input("Enter numbers separated by space ")


numberList = numbers.split()

print("\n")
print("All entered numbers ", numberList)

# Calculating the sum of all user entered numbers


sum1 = 0
for num in numberList:
sum1 += int(num)
print("Sum of all entered numbers = ", sum1)

# Calculating the average of all user entered numbers


average = sum1 / len(numberList)
print("Average of all entered numbers = ", average)

5. Print all Numbers in a Range Divisible by a Given Number

lower=int(input("Enter lower range limit:"))


upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)

6. to Print Odd Numbers Within a Given Range

lower=int(input("Enter the lower limit for the range:"))


upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)

7. Write a Python program to count the number of even and odd numbers from a series of
numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
8. Write a Python program that accepts a string and calculate the number of digits and letters.
s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
count number of vowels
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

10 count number of lower and upper case


string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
11. multiplication table
n=int(input("Enter the number to print the tables for:"))
for i in range(1,11):
print(n,"x",i,"=",n*i)

12.Square of number with in given limit


l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
13. reverse the contents of a list
a=[1,2,3,4,6,7,8,9]
for i in range(len(a)+1,0,-1):
print(i)

while loop
1.sum and average

n = 20
total_numbers = n
sum=0
while (n >= 0):
sum += n
n-=1
print ("sum using while loop ", sum)
average = sum / total_numbers
print("Average using a while loop ", average)

2. to Count the Number of Digits in a Number

n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)

3. Reverse of given number

n=int(input("Enter number: "))


rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
4. palindrome number
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

Matrix Addition

matrixOne = [[6,9,11],
[2 ,3,8]]

matrixTwo = [[15,18,11],
[26,16,19]]

result = [[0,0,0],
[0,0,0]]

# First iterate rows


for i in range(len(matrixOne)):
# Second iterate columns
for j in range(len(matrixOne[0])):
result[i][j] = matrixOne[i][j] + matrixTwo[i][j]
print("Addition of two Matrix In Python")
for res in result:
print(res)

1. to Form a New String Made of the First 2 and Last 2 characters From a Given String
2. to Calculate the Length of a String Without Using a Library Function

3. Program to Print Table of a Given Number


4. Program to check Armstrong number or not

Break statement in for loop


myStr = "jargon"
for i in myStr:
if i == "r":
break
print(i)
Continue statement in for loop
myStr = "jargon"
for i in myStr:
if i == "r":
continue
print(i)
else statement with for loop
myStr = "jargon"
for i in myStr:
if i == "r":
break
print(i)
else:
print("no break found")

note : The
else statement gets executed after the for loop execution.
However, if the loop contains the break statement, it will not execute
the else statement and also comes out of the loop.

Break with while


i=0
while i < 10:
print(i)
if i == 5:
break
i=i+1
Functions

1. Argument order
def add(num1, num2):
return num1 + num2
sum1 = add(200, 300)
sum2 = add(8, 90)
print(sum1)
print(sum2)
sum3=add(num2=300,num1=100)
print(sum3)
____________________________
def add_r(a, b):
x=a+b
return x

def add_n(a, b):


x=a+b
print (x)

print (add_r(2,3))
add_n(2,3)
____________________________________________
even odd number
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
L=[3,4,5,6,7]
for i in L:
evenOdd(i)

Program to Remove the Characters of Odd Index Values in a String


def modify(string):
final = ""
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string= input("Enter string:")
print("Modified string is:")
print(modify(string))

sum of tuple elements


def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))
default argument
def defaultArg(name, foo='Come here!'):
print (name,foo)
str = input("name:")
defaultArg(str)
defaultArg(str,"good bye")

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

variable argument
def display(*name, **address):
for items in name:
print (items)
for items in address.items():
print (items)
display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')

Nested function
def Square(X):
return (X * X)
def SumofSquares(Array, n):
Sum = 0
for i in range(n):
SquaredValue = Square(Array[i])
print(Square(Array[i]))
Sum += SquaredValue
return Sum

Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


n = len(Array)
Total = SumofSquares(Array, n)
print("Sum of the Square of List of Numbers:", Total)

__________________________________________________
def mul(x,y):
return x*y
def div(x,y):
return x/y
def sub(x,y):
return x-y
def add(x,y):
return x+y

x=int(input("enter the first number"))


y=int(input("enter the second number"))
choice=int(input("enter the choice number"))
if choice==1:
print(" mul",mul(x,y))
elif choice==2:
print("divide",div(x,y))
elif choice==3:
print("sub",sub(x,y))
elif choice==4:
print("add",add(x,y))
else:
print("wrong choice")

age = 42
name = "Dominic"
places = ["Berlin", "Cape Town", "New York"]

def info():
print("%s is % i years old." % (name, age))
return
info()

def output():

place = "Cape Town"

print("%s lives in %s." % (name, place))

return

place = "Berlin"

name = "Dominic"

print("%s lives in %s." % (name, place))

output()

___________________________________________

call by value
def val(x):

x+=1

print(id(x))

x=10

val(x)

print(id(x))

call by reference

def val(x):

x.append(4)

print(x,id(x))

x=[1,2,3]

val(x)

print(x,id(x))

x = "global"

def foo():

global x

x = "local"

print(x)

print("x is local", id(x))

print(x)

foo()

print(x)

print("x is global ",id(x))

print(x)
Class and object

class MyClass:
variable = "hello"

def function(self):
print("This is a message inside the class.")
my=MyClass()
my.function()
print(my.variable)

class MyClass:

variable = "hello"

def function(self):

print("This is a message inside the class.")

my=MyClass()

my1=MyClass()

my.function()

print(my.variable)

print()

my.function()

print(my1.variable)

__________________________________________________________________________________

class person:

age=10

def greet(self):

print("welcome")

obj=person()

obj.greet()

print(obj.age)

__________________________________________________________________________________
class add:

a=10

b=15

def num(s):

print("sum",s.a+s.b)

obj1=add()

obj2=add()

obj1.num()

obj2.num()

__________________________________________________________________________________
class num:

a=10

b=15

def add(self):

print("sum",self.a+self.b)

def sub(self):

print("sum",self.a-self.b)

def mul(self):

print("sum",self.a*self.b)

def div(self):

print("sum",self.a/self.b)

obj1=num()

obj1.add()

obj1.sub()

obj1.mul()

obj1.div()

class cal:

def add(self,x, y):

return x + y

def subtract(self,x, y):

return x - y
def multiply(self,x, y):

return x * y

def divide(self,x, y):

return x / y

print("Select operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

obj=cal()

while True:

# Take input from the user

choice = input("Enter choice(1/2/3/4): ")

# Check if choice is one of the four options

if choice in ('1', '2', '3', '4'):

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == '1':

print(num1, "+", num2, "=", obj.add(num1, num2))

elif choice == '2':

print(num1, "-", num2, "=", obj.subtract(num1, num2))

elif choice == '3':

print(num1, "*", num2, "=", obj.multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", obj.divide(num1, num2))

break

else:

print("Invalid Input")

_________________________________________________________________________________

class Vehicle:

name = ""

kind = "car"

color = ""

value = 100.00

def description(self):

desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)

return desc_str

car1=Vehicle()

car2=Vehicle()

print(car1.description())

print(car2.description())

constructor

class num:

a=0

b=0

def si(self,a,b):

self.a = a

self.b = b

def add(self):

return(self.a+self.b)

s=num()

s.si(10,30)

print(s.add())

class num:
a=0

b=0

def __init__(self,a,b):

self.a = a

self.b = b

def add(self):

return(self.a+self.b)

s=num(10,30)

print(s.add())

class Addition:

def __init__(self):

self.first = 10

self.second = 13

def display(self):

print("First number = " + str(self.first))

print("Second number = " + str(self.second))

print("Addition of two numbers = " + str(self.answer))

def calculate(self):

self.answer = self.first + self.second

# creating object of the class

# this will invoke parameterized constructor

obj = Addition()

# perform Addition

obj.calculate()

# display result
obj.display()

__________________________________________________________________________________

Constructor

class Rectangle():

def __init__(self, l, w):

self.length = l

self.width = w

def rectangle_area(self):

return self.length*self.width

newRectangle = Rectangle(12, 10)

print(newRectangle.rectangle_area())

__________________________________________________________________________________

class Circle():

def __init__(self, r):

self.radius = r

def area(self):

return self.radius**2*3.14

def perimeter(self):

return 2*self.radius*3.14

NewCircle = Circle(8)

print(NewCircle.area())

print(NewCircle.perimeter())

class cal:

def __init__(self,a,b):
self.a=a

self.b=b

def add(self):

return self.a+self.b

def mul(self):

return self.a*self.b

def div(self):

return self.a/self.b

def sub(self):

return self.a-self.b

a=int(input("Enter first number: "))

b=int(input("Enter second number: "))

obj=cal(a,b)

choice=1

while choice!=0:

print("0. Exit")

print("1. Add")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

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

if choice==1:

print("Result: ",obj.add())

elif choice==2:

print("Result: ",obj.sub())

elif choice==3:

print("Result: ",obj.mul())

elif choice==4:

print("Result: ",round(obj.div(),2))

elif choice==0:

print("Exiting!")
else:

print("Invalid choice!!")

print()

class check():

def __init__(self):

self.n=[]

def add(self,a):

return self.n.append(a)

def remove(self,b):

self.n.remove(b)

def dis(self):

return (self.n)

obj=check()

 choice=1

while choice!=0:

print("0. Exit")

print("1. Add")

print("2. Delete")

print("3. Display")

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

if choice==1:

n=int(input("Enter number to append: "))

obj.add(n)

print("List: ",obj.dis())

elif choice==2:
n=int(input("Enter number to remove: "))

obj.remove(n)

print("List: ",obj.dis())

elif choice==3:

print("List: ",obj.dis())

elif choice==0:

print("Exiting!")

else:

print("Invalid choice!!")

print()

class variable and instance variable

class std:

stream ="BCA"

def set(self, roll):

self.roll=roll

A=std()

B=std()

A.set(101)

B.set(102)

print(A.stream)

print(A.roll)

print(B.stream)

print(B.roll)

_________________________________________________________________________________
class CSStudent:
    stream = 'cse'                 
   def __init__(self,name,roll):
        self.name = name           
        self.roll = roll           
  
# Objects of CSStudent class
a = CSStudent('jack', 1)
b = CSStudent('jill', 2)
  
print(a.stream) 
print(b.stream) 
print(a.name)   
print(b.name)   
print(a.roll)   
print(b.roll)   
print(CSStudent.stream)

inheritance

single inheritance

class Parent():

def first (self):

print(“first method”)

class child(parent):

def second(self):

print(“second method”)

c=child()

c.first()

c.second()

__________________________________________________________________________________

class Animal:
def eat(self):
print("Animal eating")
def sleep(self):
print("Animal is sleeping")
class Dog(Animal) :
def bark(self):
print("Dog barking")

d=Dog()
d.bark()
d.eat()
d.sleep()
_________________________________________________________________________________
class Parent:
parentname = ""
childname = ""
 
def show_parent(self):
print(self.parentname)
 
 
# Child class created inherits Parent class
class Child(Parent):
def show_child(self):
print(self.childname)
 
 

ch1 = Child() # Object of Child class


ch1.parentname = "Mark" # Access Parent class attributes
ch1.childname = "John"
ch1.show_parent() # Access Parent class method
ch1.show_child()
__________________________________________________________________________________
class cal:
def assign(self, a, b):
self.a=a
self.b=b
def add(self):
s=(self.a+self.b)
return s
class cal1(cal):
def sub(self):
s=(self.a-self.b)
return s
c=cal1()
c.assign(1,2)
print(c.add())
print(c.sub())
__________________________________________________________________________________

Multiple inheritance using constructor


class Base1(object):
def __init__(self):
self.str1 = "BCA 1"
print("Base1")

class Base2(object):
def __init__(self):
self.str2 = "BCA 2"
print("Base2")

class Derived(Base1, Base2):


def __init__(self):

Base1.__init__(self)
Base2.__init__(self)
print("Derived")

def printStrs(self):
print(self.str1, self.str2)

ob = Derived()
ob.printStrs()
Multilevel inheritance using constructor

class Base(object):

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

class Child(Base):

# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age

# To get name
def getAge(self):
return self.age

# Inherited or Sub class (Note Person in bracket)


class GrandChild(Child):

# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address

# To get address
def getAddress(self):
return self.address

# Driver code
g = GrandChild("sjc", 132, "Bangalore")
print(g.getName(), g.getAge(), g.getAddress())

__________________________________________________________________________________
Multiple inheritance with constructor
class A:
def __init__(self):
self.name = 'John'
self.age = 23

def getName(self):
return self.name

class B:
def __init__(self):
self.name = 'Richard'
self.id = '32'

def getName(self):
return self.name

class C(A, B):


def __init__(self):
A.__init__(self)
B.__init__(self)

def getName(self):
return self.name

C1 = C()
print(C1.getName())
super keyword with single inheritance

class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')

class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')

d1 = Dog()

_________________________________________________________________________________

Super Keyword with multiple inheritance

class A:
def __init__(self):
super().__init__()
self.name = 'John'
self.age = 23

def getName(self):
return self.name

class B:
def __init__(self):
super().__init__()
self.name = 'Richard'
self.id = '32'

def getName(self):
return self.name

class C(B, A):


def __init__(self):
super().__init__()

def getName(self):
return self.name

C1 = C()
print(C1.getName())

class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');

# Mammal inherits Animal


class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a mammal.')
super().__init__(mammalName)

# CannotFly inherits Mammal


class CannotFly(Mammal):
def __init__(self, mammalThatCantFly):
print(mammalThatCantFly, "cannot fly.")
super().__init__(mammalThatCantFly)

# CannotSwim inherits Mammal


class CannotSwim(Mammal):
def __init__(self, mammalThatCantSwim):
print(mammalThatCantSwim, "cannot swim.")
super().__init__(mammalThatCantSwim)

# Cat inherits CannotSwim and CannotFly


class Cat(CannotSwim, CannotFly):
def __init__(self):
print('I am a cat.');
super().__init__('Cat')
# Driver code
cat = Cat()
print('')
bat = CannotSwim('Bat')

Super keyword with multilevel inheritance

class A:
def __init__(self):
print('Initializing: class A')
def sub_method(self, b):
print('Printing from class A:', b)
class B(A):
def __init__(self):
print('Initializing: class B')
super().__init__()

def sub_method(self, b):


print('Printing from class B:', b)
super().sub_method(b + 1)
class C(B):
def __init__(self):
print('Initializing: class C')
super().__init__()

def sub_method(self, b):


print('Printing from class C:', b)
super().sub_method(b + 1)
c = C()
c.sub_method(1)

Data abstraction in python

Public access modifier

class std:
def __init__(self, name):
self.Name = name

def displayAge(self):
print("Age: ", self.Name)

obj = std("jack")
obj.displayAge()
Private Access Modifier

class MyClass:

# Hidden member of MyClass


__hiddenVariable = 0

# A member method that changes


# __hiddenVariable
def add(self, increment):
self.__hiddenVariable += increment
print (self.__hiddenVariable)

# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)

We can access the value of hidden attribute by a tricky syntax:

# A Python program to demonstrate that hidden


# members can be accessed outside a class
class MyClass:

# Hidden member of MyClass


__hiddenVariable = 10

# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
__________________________________________________________________________________

# program to illustrate private access modifier in a class

class std:

# private members
__name = None
__roll = None
__branch = None

# constructor
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
# private member function
def __displayDetails(self):

# accessing private data members


print("Name: ", self.__name)
print("Roll: ", self.__roll)
print("Branch: ", self.__branch)

# public member function


def accessPrivateFunction(self):

# accesing private member function


self.__displayDetails()

# creating object
obj = Geek("jack", 17bca06256, "python ")

# calling public member function of the class


obj.accessPrivateFunction()

__________________________________________________________________________________

All in one program

class Company:

# constructor

def __init__(self, name, proj):

self.name = name # name(name of company) is public

self._proj = proj # proj(current project) is protected

# public function to show the details

def show(self):

print("The code of the company is = ",self.ccode)

# define child class Emp

class Emp(Company):

# constructor

def __init__(self, eName, sal, cName, proj):

# calling parent class constructor

Company.__init__(self, cName, proj)


self.name = eName # public member variable

self.__sal = sal # private member variable

# public function to show salary details

def show_sal(self):

print("The salary of ",self.name," is ",self.__sal,)

# creating instance of Company class

c = Company("Stark Industries", "Mark 4")

# creating instance of Employee class

e = Emp("Steve", 9999999, c.name, c._proj)

print("Welcome to ", c.name)

print("Here ", e.name," is working on ",e._proj)

# only the instance itself can change the __sal variable

# and to show the value we have created a public function show_sal()

e.show_sal()

Polymorphism

class India():
     def capital(self):
       print("New Delhi")
 
     def language(self):
       print("Hindi and English")
 
class USA():
     def capital(self):
       print("Washington, D.C.")
 
     def language(self):
       print("English")
 
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()

class Square:

side = 5

def calculate_area(self):

return self.side * self.side

class Triangle:

base = 5

height = 4

def calculate_area(self):

return 0.5 * self.base * self.height

sq = Square()

tri = Triangle()

print("Area of square: ", sq.calculate_area())

print("Area of triangle: ", tri.calculate_area())

Method Overloading
class OverloadDemo:
 
def add (self, *a ) :
# variable to hold sum of numbers
sum = 0
# iterate over the arguments
for num in a:
# add numbers
sum = sum + num
return sum
 
# create object of class
obj = OverloadDemo ()
# call method with 5 arguments
sum = obj. add(1,2,3,4,5)
print("Sum of 5 numbers is " + str(sum))
# call method with 4 arguments
sum = obj. add(1,2,3,4)
print("Sum of 4 numbers is " + str(sum))
# call method with 3 argument
sum = obj. add(1,2,3)
print("Sum of 3 numbers is " + str(sum))
# call method with 0 argument
sum = obj. add()
print("Sum of 0 numbers is " + str(sum))

method overriding

class Animal:
multicellular = True
eukaryotic = True
def breathe(self):
print("I breathe oxygen.")
def feed(self):
print("I eat food.")

class Herbivorous(Animal):
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()
herbi.feed()
herbi.breathe()
__________________________________________________________________________________
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
print(self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()

class Employee:
def message(self):
print('This message is from Employee Class')

class Department(Employee):

def message(self):
print('This Department class is inherited from Employee')

class Sales(Employee):

def message(self):
print('This Sales class is inherited from Employee')

emp = Employee()
emp.message()

print('------------')
dept = Department()
dept.message()

print('------------')
sl = Sales()
sl.message()
________________________________________________________________________________
how to use method overriding in Multiple inheritance
class Employee:

def add(self, a, b):


print('The Sum of Two = ', a + b)

class Department(Employee):

def add(self, a, b, c):


print('The Sum of Three = ', a + b + c)

emp = Employee()
emp.add(10, 20)
print('------------')
dept = Department()
dept.add(50, 130, 90)
________________________________________________________________________________
calling superclass method within the overridden method

class Employee:
   
   def message(self):
       print('This message is from Employee Class')
 
class Department(Employee):
 
   def message(self):
       Employee.message(self)
       print('This Department class is inherited from Employee')
 
emp = Employee()
emp.message()
 
print('------------')
dept = Department()
dept.message()

Operator overloading

print(1+2)

print("a"+"b")

print(int.__add__(1,2))

print(int.__sub__(2,1))

print(str.__add__("a","b"))

a= 1

b=2

print(a+b)

print(a.__add__(b))

a = ' Python'

b = ['c ', 'Python']

print(len(a))

print(a.__len__())

built-in class of int and str class

class int:

def __add__(self *a)

class str:
def __add__(self *a)

__________________________________________________________________________________

Passing one argument to + operator

class A:
def __init__(self, a):
self.a = a

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("python")
ob4 = A("For")

print(ob1 + ob2)
print(ob3 + ob4)

Passing two argument to + operator

class complex:

def __init__(self, a, b):

self.a = a

self.b = b

def __add__(self, other):

return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)

Ob2 = complex(2, 3)

Ob3 = Ob1 + Ob2

print(Ob3)

Passing two argument to + operator and return with object of class

class std:

def __init__(self,m1,m2):
self.m1=m1

self.m2=m2

def __add__(self,other):

m1=self.m1+other.m1

m2=self.m2+other.m2

s3=std(m1,m2)

return s3

s1=std(58,69)

s2=std(70,60)

s3=s1+s2

print(s3.m1)

print(s3.m2)

__________________________________________________________________________________

GREATER THAN OPERATOR

class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
overriding absolute function
class Vector:
def __init__(self, x_comp, y_comp):
self.x_comp = x_comp
self.y_comp = y_comp
def __abs__(self):
return (self.x_comp ** 2 + self.y_comp ** 2) ** 0.5
def add(self):
return (self.x_comp ** 2 + self.y_comp ** 2) ** 0.5
vector = Vector(2, 4)
print(vector.add())
print(abs(vector))
import math

class Circle:

    def __init__(self, radius):


        self.__radius = radius

    def setRadius(self, radius):


        self.__radius = radius

    def getRadius(self):
        return self.__radius

    def area(self):
        return math.pi * self.__radius ** 2

    def __add__(self, another_circle):


        return Circle( self.__radius + another_circle.__radius )

c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a     method


named __add__
print(c3.getRadius())
class Circle:

def __init__(self, radius):


self.__radius = radius

def setRadius(self, radius):


self.__radius = radius

def getRadius(self):
return self.__radius

def area(self):
return math.pi * self.__radius ** 2

def __add__(self, another_circle):


return Circle( self.__radius + another_circle.__radius )

def __gt__(self, another_circle):


return self.__radius > another_circle.__radius

def __lt__(self, another_circle):


return self.__radius < another_circle.__radius

def __str__(self):
return "Circle with radius " + str(self.__radius)
c1 = Circle(4)
print(c1.getRadius())

c2 = Circle(5)
print(c2.getRadius())

c3 = c1 + c2
print(c3.getRadius())

print( c3 > c2) # Became possible because we have added __gt__ method

print( c1 < c2) # Became possible because we have added __lt__ method

print(c3)

square = lambda x : x * x
square (5)

def square(x):
return (x * x)

x = lambda a : a + 10
print(x(5))

x = lambda a, b : a * b
print(x(5, 6))

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

disp = lambda str: print('Output: ' + str)


disp("Hello World!")

__________________________________________________________________________________

class Component:

# composite class constructor

def __init__(self):

print('Component class object created...')

# composite class instance method

def m1(self):
print('Component class m1() method executed...')

class Composite:

# composite class constructor

def __init__(self):

# creating object of component class

self.obj1 = Component()

print('Composite class object also created...')

# composite class instance method

def m2(self):

print('Composite class m2() method executed...')

# calling m1() method of component class

self.obj1.m1()

# creating object of composite class

obj2 = Composite()

# calling m2() method of composite class

obj2.m2()

Composition

class Salary:
def __init__(self, pay):

self.pay = pay

def get_total(self):

return (self.pay*12)

 class Employee:

def __init__(self, pay, bonus):

self.pay = pay

self.bonus = bonus

self.obj_salary = Salary(self.pay)

def annual_salary(self):

return "Total: " + str(self.obj_salary.get_total() + self.bonus)

 obj_emp = Employee(600, 500)

print(obj_emp.annual_salary())

_________________________________________________________________________________

aggregation

class Salary:

def __init__(self, pay):

self.pay = pay

def get_total(self):

return (self.pay*12)

class Employee:

def __init__(self, pay, bonus):

self.pay = pay

self.bonus = bonus
 

def annual_salary(self):

return "Total: " + str(self.pay.get_total() + self.bonus)

obj_sal = Salary(600)

obj_emp = Employee(obj_sal, 500)

print(obj_emp.annual_salary())

randomList = ['a', 0, 2]

for entry in randomList:

try:

print("The entry is", entry)

r = 1/int(entry)

break

except:

print("Oops! error occurred.")

print("Next entry.")

print()

print("The reciprocal of", entry, "is", r)

# Static Method Implementation in python

class Student:

name = 'Student'

def __init__(self, a, b):

self.a = a

self.b = b

@staticmethod

def info():

return "This is a student class"


print(Student.info())

# Class Method Implementation in python

class Student:

name = 'Student'

def __init__(self, a, b):

self.a = a

self.b = b

@classmethod

def info(cls):

return cls.name

print(Student.info())

(x,y) = (5,0)

try:

z = x/y

except ZeroDivisionError as e:

z=e

print (z)

try:
l = [1, 2, 3]
l[4]

except IndexError as e:
print(e)

try:

value_one=int(input("Enter First Number:"))


value_second=int(input("Enter Second Number:"))

print("The Result:",value_one/value_second)

except ZeroDivisionError:

print("Cannot Divide with Zero")

except ValueError:

print("Please Provide int values only")

__________________________________________________________________________________

try:

x=1

y=2

print(x/y)

except TypeError:

print( " str")

except NameError:

print("name not defined")

print("out")

__________________________________________________________________________________

try:

x=1

y=2

print(x/y)

except (TypeError,NameError):

print( " str")

print("name not defined")

print("out")

try:
c = a/b

except ZeroDivisionError:

print “you tried to divide by zero”

except TypeError:

print “one of the items you entered was not a number

except:

print “there is an unknown problem with a value you entered”

else:

print “the input is good”

try:

x=int(input('Enter a number upto 100: ‘))

if x > 100:

raise ValueError(x)

except ValueError:

print(x, "is out of allowed range")

else:

print(x,"is within the allowed range")

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

x=1
try:
if x >10:
Ex = ValueError()
Ex.sterror = "Value must be within 1 and 10."
raise Ex
except ValueError as e:
print("ValueError Exception!", e.sterror)
try:
raise MemoryError(“memory Error”)
except MemoryError as e
print(e)

define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

class A(Exception)

def ___init__(self,msg)

self.msg=msg
def print(self)

print(“user defined exception”,self.msg)

try:

raise A (“Welcome”)

except A as e:

e.print()

class Invalid(Exception):

def __init__(self,msg):

self.msg=msg

l=-1

try :

if l < 1:

raise invalid(“invalid use”)

except invalid as e:

print(e.msg)

class SalaryNotInRangeError(Exception):

"""Exception raised for errors in the input salary.

Attributes:

salary -- input salary which caused the error

message -- explanation of the error

"""

def __init__(self, salary, message="Salary is not in (5000, 15000) range"):

self.salary = salary

self.message = message

super().__init__(self.message)

salary = int(input("Enter salary amount: "))


if not 5000 < salary < 15000:

raise SalaryNotInRangeError(salary)

__________________________________________________________________________________

from tkinter import *  
  
top = Tk()  
  
top.geometry("400x250")  
  
name = Label(top, text = "Name").place(x = 30,y = 50)  
  
email = Label(top, text = "Email").place(x = 30, y = 90)  
  
password = Label(top, text = "Password").place(x = 30, y = 130)  
  
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place(
x = 30, y = 170)  
  
e1 = Entry(top).place(x = 80, y = 50)  
  
  
e2 = Entry(top).place(x = 80, y = 90)  
  
  
e3 = Entry(top).place(x = 95, y = 130)  
  
top.mainloop()  

import tkinter as tk  
from functools import partial  
   
   
def call_result(label_result, n1, n2):  
    num1 = (n1.get())  
    num2 = (n2.get())  
    result = int(num1)+int(num2)  
    label_result.config(text="Result = %d" % result)  
    return  
   
root = tk.Tk()  
root.geometry('400x200+100+200')  
  
root.title('Calculator')  
   
number1 = tk.StringVar()  
number2 = tk.StringVar()  
  
labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)  
  
labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)  
  
labelResult = tk.Label(root)  
  
labelResult.grid(row=7, column=2)  
  
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)  
  
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)  
  
call_result = partial(call_result, labelResult, number1, number2)  
  
buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3, column=0)  
  
root.mainloop()  
# Program to make a simple

import tkinter as tk

root=tk.Tk()

# setting the windows size


root.geometry("600x400")

# declaring string variable


# for storing name and password
name_var=tk.StringVar()
passw_var=tk.StringVar()

# defining a function that will


# get the name and password and
# print them on the screen
def submit():

name=name_entry.get()
password=passw_var.get()
print("The name is : " + name)
print("The password is : " + password)
name_var.set("")
passw_var.set("")

# creating a label for


# name using widget Label
name_label = tk.Label(root, text = 'Username',
font=('calibre',
10, 'bold'))

# creating a entry for input


# name using widget Entry
name_entry = tk.Entry(root,
textvariable = name_var,f
ont=('calibre',10,'normal'))

# creating a label for password


passw_label = tk.Label(root,
text = 'Password',
font = ('calibre',10,'bold'))

# creating a entry for password


passw_entry=tk.Entry(root,
textvariable = passw_var,
font = ('calibre',10,'normal'),
show = '*')

# creating a button using the widget


# Button that will call the submit function
sub_btn=tk.Button(root,text = 'Submit',
command = submit)

# placing the label and entry in


# the required position using grid
# method
name_label.grid(row=0,column=0)
name_entry.grid(row=0,column=1)
passw_label.grid(row=1,column=0)
passw_entry.grid(row=1,column=1)
sub_btn.grid(row=2,column=1)

# performing an infinite loop


# for the window to display
root.mainloop()

import re
txt="12abc3;\"*erw345"
print(re.findall("\W",txt))

import re
txt="12abc5; \"*erw345"
print(re.findall("c5\Z",txt))

import re
string = '39801 356, 2102 1111'
pattern = '(\d{3}) (\d{2})'
match = re.findall(pattern, string)
print(match)

import re
txt = "Therain in Spain"
x = re.findall("\s", txt)

import re
s="sat rat mat eat"
print(re.findall("[srme]at",s))

import re
s="sat rat mat eat"
print(re.findall("[sre]a*t",s))
import re
print(re.search("n","\n"))
print(re.findall("n", r"\n\n\n"))
print(re.findall("bab","bab ab abc"))
print(re.findall(r"ab\b","bab ab abc"))
print(re.findall('[a-z]','avb bavz'))
print(re.findall('[a\-z]','avb -zavz'))
print(re.findall('[a-z][0-9]','avb bavz67'))
print(re.findall('[(+*)]','a+vb bavz*67'))
print(re.findall('[a+b*]','aaaa+vb bavz*67'))
print(re.findall('a+b*','aaaa+vb bavz*67'))

print(re.findall(r"ab\b","bab ab abc"))
print(re.findall('[a-z]','avb bavz'))
print(re.findall('a+b*','aaaa+vb bavz*67'))
_______________________________________________________
import re
print(re.search("n","\n"))
print(re.findall("\n","\n\n\n"))
print(re.findall("\n","\n"))
print(re.findall("n",r"\n\n\n"))

import re
print(re.findall("n","\\n\\n\\n"))
print(re.findall("n",r"\n\n\n"))
print(re.findall("\bab","ab ab abc"))
print(re.findall(r"\bab","ab ab babc"))
print(re.findall(r"ab\b","ab ab babc"))
print(re.search(r"ab\b","ab ab babc"))

output

['n', 'n', 'n']


['n', 'n', 'n']
[]
['ab', 'ab']
['ab', 'ab']
<re.Match object; span=(0, 2), match='ab'>

print(re.findall('[a-z]','aVb Kavz'))
print(re.findall('[a\-z]','avb -zavz'))

output

['a', 'b', 'a', 'v', 'z']


['a', '-', 'z', 'a', 'z']
_______________________________________________________
print(re.findall('[a-z][0-9]','avb bavz67'))
print(re.findall('[(+*)]','a+vb avz*67'))

print(re.findall('[a+b*]','aaaa+vb bavz*67'))
print(re.findall('a+b*','aaaa+vb bavz*67'))
output
['z6']
['+', '*']
['a', 'a', 'a', 'a', '+', 'b', 'b', 'a', '*']
['aaaa', 'a']
print(re.findall('[-z]','aVb Kavz'))
print(re.findall('[z-]','avb -zavz'))
print(re.findall('[^-z]','aVb Kavz'))

output

['z']
['-', 'z', 'z']
['a', 'V', 'b', ' ', 'K', 'a', 'v']

import re

string = 'hello 12 hi 89. Howdy 34'


pattern = '\d+'

result = re.findall(pattern, string)

print(result)

import re
regex = "([a-zA-Z]+) (\d+)"
print(re.search(regex, " welcome June 24"))

________________________________________________________
import re
string_one = 'file_record_transcript.pdf'
string_two = 'file_07241999.pdf'
string_three = 'testfile_fake.pdf.tmp'

pattern = '^(file.+)\.pdf$'
a = re.search(pattern, string_one)
b = re.search(pattern, string_two)
c = re.search(pattern, string_three)
print(a)
print(b)
print(c)
import re

pattern=re.compile('AV')

result=pattern.findall('AV Analytics Vidhya AV')

print result

result2=pattern.findall('AV is largest analytics community of India')

print result2

Output:

['AV', 'AV']

['AV']

import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'

# empty string
replace = ''

new_string = re.sub(pattern, replace, string)


print(new_string)

_
result=re.split(r'i','Analytics Vidhya')

print result

Output: ['Analyt', 'cs V', 'dhya']

Code

result=re.split(r'i','Analytics Vidhya',maxsplit=1)

print result

import re

text = '''
Ha! let me see her: out, alas! he's cold:
Her blood is settled, and her joints are stiff;
Life and these lips have long been separated:
Death lies on her like an untimely frost
Upon the sweetest flower of all the field.
'''

print(re.findall('HER', text, flags=re.IGNORECASE))


print(re.findall(' HER # Ignored', text, flags=re.IGNORECASE + re.VERBOSE))
print( re.findall(“HER”, text_str, re.IGNORECASE | re.DOTALL)

1. Extract each character (using “\w“)

import re

result=re.findall(r'.','AV is largest of India')

print result
2. now to avoid it use “\w” instead of “.“.

result=re.findall(r'\w','AV is largest of India')

print result

3. Extract each word (using “*” or “+“)

result=re.findall(r'\w*','AV is largest of India')

print (result)

4. Again, it is returning space as a word because “*” returns zero or more matches of pattern
to its left. Now to remove spaces we will go with “+“.

result=re.findall(r'\w+','AV is largest of India')

5. print result  Extract each word (using “^“)

result=re.findall(r'^\w+','AV is largest of India')

print (result)

6. If we will use “$” instead of “^”, it will return the word from the end of the string.

result=re.findall(r'\w+$','AV is largest of India')

print (result)

You might also like