Python Class Prg
Python Class Prg
n = 10
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )
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 )
numberList = [Link]()
print("\n")
sum1 = 0
sum1 += int(num)
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 [Link]():
d=d+1
elif [Link]():
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)
while loop
[Link] and average
n = 20
total_numbers = n
sum=0
sum += n
n-=1
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
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]]
for j in range(len(matrixOne[0])):
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
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
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)
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 [Link]():
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
age = 42
name = "Dominic"
places = ["Berlin", "Cape Town", "New York"]
def info():
print("%s is % i years old." % (name, age))
return
info()
def output():
return
place = "Berlin"
name = "Dominic"
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):
[Link](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)
foo()
print(x)
print(x)
class MyClass:
variable = "hello"
def function(self):
print("This is a message inside the class.")
my=MyClass()
[Link]()
print([Link])
class MyClass:
variable = "hello"
def function(self):
my=MyClass()
my1=MyClass()
[Link]()
print([Link])
print()
[Link]()
print([Link])
__________________________________________________________________________________
class person:
age=10
def greet(self):
print("welcome")
obj=person()
[Link]()
print([Link])
__________________________________________________________________________________
class add:
a=10
b=15
def num(s):
print("sum",s.a+s.b)
obj1=add()
obj2=add()
[Link]()
[Link]()
__________________________________________________________________________________
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()
[Link]()
[Link]()
[Link]()
[Link]()
class cal:
return x + y
return x - y
return x * y
return x / y
print("Select operation.")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
obj=cal()
while True:
if choice == '1':
break
else:
print("Invalid Input")
_________________________________________________________________________________
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
car1=Vehicle()
car2=Vehicle()
print([Link]())
print([Link]())
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()
[Link](10,30)
print([Link]())
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([Link]())
class Addition:
def __init__(self):
[Link] = 10
[Link] = 13
def display(self):
def calculate(self):
obj = Addition()
# perform Addition
[Link]()
# display result
[Link]()
__________________________________________________________________________________
Constructor
class Rectangle():
[Link] = l
[Link] = w
def rectangle_area(self):
return [Link]*[Link]
newRectangle = Rectangle(12, 10)
print(newRectangle.rectangle_area())
__________________________________________________________________________________
class Circle():
[Link] = r
def area(self):
return [Link]**2*3.14
def perimeter(self):
return 2*[Link]*3.14
NewCircle = Circle(8)
print([Link]())
print([Link]())
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: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice==1:
print("Result: ",[Link]())
elif choice==2:
print("Result: ",[Link]())
elif choice==3:
print("Result: ",[Link]())
elif choice==4:
print("Result: ",round([Link](),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
class check():
def __init__(self):
self.n=[]
def add(self,a):
return [Link](a)
def remove(self,b):
[Link](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")
if choice==1:
[Link](n)
print("List: ",[Link]())
elif choice==2:
[Link](n)
print("List: ",[Link]())
elif choice==3:
print("List: ",[Link]())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
class std:
stream ="BCA"
[Link]=roll
A=std()
B=std()
[Link](101)
[Link](102)
print([Link])
print([Link])
print([Link])
print([Link])
_________________________________________________________________________________
class CSStudent:
stream = 'cse'
def __init__(self,name,roll):
[Link] = name
[Link] = roll
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
inheritance
single inheritance
class Parent():
print(“first method”)
class child(parent):
def second(self):
print(“second method”)
c=child()
[Link]()
[Link]()
__________________________________________________________________________________
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()
[Link]()
[Link]()
[Link]()
_________________________________________________________________________________
class Parent:
parentname = ""
childname = ""
def show_parent(self):
print([Link])
class Base2(object):
def __init__(self):
self.str2 = "BCA 2"
print("Base2")
Base1.__init__(self)
Base2.__init__(self)
print("Derived")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
[Link]()
Multilevel inheritance using constructor
class Base(object):
# Constructor
def __init__(self, name):
[Link] = name
# To get name
def getName(self):
return [Link]
class Child(Base):
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
[Link] = age
# To get name
def getAge(self):
return [Link]
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
[Link] = address
# To get address
def getAddress(self):
return [Link]
# Driver code
g = GrandChild("sjc", 132, "Bangalore")
print([Link](), [Link](), [Link]())
__________________________________________________________________________________
Multiple inheritance with constructor
class A:
def __init__(self):
[Link] = 'John'
[Link] = 23
def getName(self):
return [Link]
class B:
def __init__(self):
[Link] = 'Richard'
[Link] = '32'
def getName(self):
return [Link]
def getName(self):
return [Link]
C1 = C()
print([Link]())
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()
_________________________________________________________________________________
class A:
def __init__(self):
super().__init__()
[Link] = 'John'
[Link] = 23
def getName(self):
return [Link]
class B:
def __init__(self):
super().__init__()
[Link] = 'Richard'
[Link] = '32'
def getName(self):
return [Link]
class C(B, A):
def __init__(self):
super().__init__()
def getName(self):
return [Link]
C1 = C()
print([Link]())
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');
# Driver code
cat = Cat()
print('')
bat = CannotSwim('Bat')
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__()
class std:
def __init__(self, name):
[Link] = name
def displayAge(self):
print("Age: ", [Link])
obj = std("jack")
[Link]()
class MyClass:
# Driver code
myObject = MyClass()
[Link](2)
[Link](5)
# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
__________________________________________________________________________________
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
# creating object
obj = Geek("jack", 17bca06256, "python ")
__________________________________________________________________________________
class Company:
# constructor
def show(self):
class Emp(Company):
# constructor
def show_sal(self):
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):
[Link]()
[Link]()
class Square:
side = 5
def calculate_area(self):
class Triangle:
base = 5
height = 4
def calculate_area(self):
sq = Square()
tri = Triangle()
Method Overloading
class OverloadDemo:
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()
[Link]()
[Link]()
__________________________________________________________________________________
class Rectangle():
def __init__(self,length,breadth):
[Link] = length
[Link] = breadth
def getArea(self):
print([Link]*[Link]," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
[Link] = side
Rectangle.__init__(self,side,side)
def getArea(self):
print([Link]*[Link]," is area of square")
s = Square(4)
r = Rectangle(2,4)
[Link]()
[Link]()
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()
[Link]()
print('------------')
dept = Department()
[Link]()
print('------------')
sl = Sales()
[Link]()
________________________________________________________________________________
how to use method overriding in Multiple inheritance
class Employee:
class Department(Employee):
emp = Employee()
[Link](10, 20)
print('------------')
dept = Department()
[Link](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):
[Link](self)
print('This Department class is inherited from Employee')
emp = Employee()
[Link]()
print('------------')
dept = Department()
[Link]()
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'
print(len(a))
print(a.__len__())
class int:
class str:
__________________________________________________________________________________
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
class complex:
self.a = a
self.b = b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
print(Ob3)
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)
__________________________________________________________________________________
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([Link]())
print(abs(vector))
import math
class Circle:
def area(self):
return [Link] * self.__radius ** 2
c1 = Circle(4)
print([Link]())
c2 = Circle(5)
print([Link]())
def getRadius(self):
return self.__radius
def area(self):
return [Link] * self.__radius ** 2
def __str__(self):
return "Circle with radius " + str(self.__radius)
c1 = Circle(4)
print([Link]())
c2 = Circle(5)
print([Link]())
c3 = c1 + c2
print([Link]())
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))
__________________________________________________________________________________
class Component:
def __init__(self):
def m1(self):
class Composite:
# composite class constructor
def __init__(self):
self.obj1 = Component()
def m2(self):
self.obj1.m1()
obj2 = Composite()
obj2.m2()
Composition
class Salary:
[Link] = pay
def get_total(self):
return ([Link]*12)
class Employee:
[Link] = pay
[Link] = bonus
self.obj_salary = Salary([Link])
def annual_salary(self):
print(obj_emp.annual_salary())
_________________________________________________________________________________
aggregation
class Salary:
[Link] = pay
def get_total(self):
return ([Link]*12)
class Employee:
[Link] = pay
[Link] = bonus
def annual_salary(self):
print(obj_emp.annual_salary())
randomList = ['a', 0, 2]
try:
r = 1/int(entry)
break
except:
print("Next entry.")
print()
class Student:
name = 'Student'
self.a = a
self.b = b
@staticmethod
def info():
print([Link]())
# Class Method Implementation in python
class Student:
name = 'Student'
self.a = a
self.b = b
@classmethod
def info(cls):
return [Link]
print([Link]())
(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:
print("The Result:",value_one/value_second)
except ZeroDivisionError:
except ValueError:
__________________________________________________________________________________
try:
x=1
y=2
print(x/y)
except TypeError:
except NameError:
print("out")
__________________________________________________________________________________
try:
x=1
y=2
print(x/y)
except (TypeError,NameError):
print("out")
try:
c = a/b
except ZeroDivisionError:
except TypeError:
except:
else:
try:
if x > 100:
raise ValueError(x)
except ValueError:
else:
x = "hello"
x=1
try:
if x >10:
Ex = ValueError()
[Link] = "Value must be within 1 and 10."
raise Ex
except ValueError as e:
print("ValueError Exception!", [Link])
try:
raise MemoryError(“memory Error”)
except MemoryError as e
print(e)
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
class A(Exception)
def ___init__(self,msg)
[Link]=msg
def print(self)
try:
raise A (“Welcome”)
except A as e:
[Link]()
class Invalid(Exception):
def __init__(self,msg):
[Link]=msg
l=-1
try :
if l < 1:
except invalid as e:
print([Link])
class SalaryNotInRangeError(Exception):
Attributes:
"""
[Link] = salary
[Link] = message
super().__init__([Link])
raise SalaryNotInRangeError(salary)
__________________________________________________________________________________
from tkinter import *
top = Tk()
[Link]("400x250")
[Link]()
import tkinter as tk
from functools import partial
root = [Link]()
[Link]('400x200+100+200')
[Link]('Calculator')
number1 = [Link]()
number2 = [Link]()
[Link](row=7, column=2)
[Link]()
# Program to make a simple
import tkinter as tk
root=[Link]()
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 = [Link](root, text = 'Username',
font=('calibre',
10, 'bold'))
import re
txt="12abc3;\"*erw345"
print([Link]("\W",txt))
import re
txt="12abc5; \"*erw345"
print([Link]("c5\Z",txt))
import re
string = '39801 356, 2102 1111'
pattern = '(\d{3}) (\d{2})'
match = [Link](pattern, string)
print(match)
import re
txt = "Therain in Spain"
x = [Link]("\s", txt)
import re
s="sat rat mat eat"
print([Link]("[srme]at",s))
import re
s="sat rat mat eat"
print([Link]("[sre]a*t",s))
import re
print([Link]("n","\n"))
print([Link]("n", r"\n\n\n"))
print([Link]("bab","bab ab abc"))
print([Link](r"ab\b","bab ab abc"))
print([Link]('[a-z]','avb bavz'))
print([Link]('[a\-z]','avb -zavz'))
print([Link]('[a-z][0-9]','avb bavz67'))
print([Link]('[(+*)]','a+vb bavz*67'))
print([Link]('[a+b*]','aaaa+vb bavz*67'))
print([Link]('a+b*','aaaa+vb bavz*67'))
print([Link](r"ab\b","bab ab abc"))
print([Link]('[a-z]','avb bavz'))
print([Link]('a+b*','aaaa+vb bavz*67'))
_______________________________________________________
import re
print([Link]("n","\n"))
print([Link]("\n","\n\n\n"))
print([Link]("\n","\n"))
print([Link]("n",r"\n\n\n"))
import re
print([Link]("n","\\n\\n\\n"))
print([Link]("n",r"\n\n\n"))
print([Link]("\bab","ab ab abc"))
print([Link](r"\bab","ab ab babc"))
print([Link](r"ab\b","ab ab babc"))
print([Link](r"ab\b","ab ab babc"))
output
output
print([Link]('[a+b*]','aaaa+vb bavz*67'))
print([Link]('a+b*','aaaa+vb bavz*67'))
output
['z6']
['+', '*']
['a', 'a', 'a', 'a', '+', 'b', 'b', 'a', '*']
['aaaa', 'a']
print([Link]('[-z]','aVb Kavz'))
print([Link]('[z-]','avb -zavz'))
print([Link]('[^-z]','aVb Kavz'))
output
['z']
['-', 'z', 'z']
['a', 'V', 'b', ' ', 'K', 'a', 'v']
import re
pattern = '\d+'
import re
regex = "([a-zA-Z]+) (\d+)"
print([Link](regex, " welcome June 24"))
________________________________________________________
import re
string_one = 'file_record_transcript.pdf'
string_two = 'file_07241999.pdf'
string_three = 'testfile_fake.[Link]'
pattern = '^(file.+)\.pdf$'
a = [Link](pattern, string_one)
b = [Link](pattern, string_two)
c = [Link](pattern, string_three)
print(a)
print(b)
print(c)
import re
pattern=[Link]('AV')
print result
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 = ''
_
result=[Link](r'i','Analytics Vidhya')
print result
Code
result=[Link](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.
'''
import re
print result
print (result)
print (result)
6. If we will use “$” instead of “^”, it will return the word from the end of
the string.
print (result)