Skip to content

Commit f187d18

Browse files
committed
Python Programs
1 parent e7940ee commit f187d18

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+7532
-0
lines changed

OOP/P01_ClassDefinition.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#In this program we will see how to define a class
2+
3+
class MyFirstClass():
4+
#Class Attributes
5+
var = 10
6+
7+
firstObject = MyFirstClass()
8+
print(firstObject) #Printing object's memory hex
9+
print(firstObject.var) #Accessing Class Attributes
10+
11+
secondObject = MyFirstClass()
12+
print(secondObject)
13+
print(secondObject.var)

OOP/P02_InstanceMethods.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#In this example we will be seeing how instance methods are used
2+
#Instance methods are accessed by: instance.method()
3+
4+
class Vehicle():
5+
#Class Methods/ Attributes
6+
7+
#Here self is passed as an argument because instance is passed as first argument
8+
def type(self): #Without self it throws an error
9+
print(self)
10+
print('I have a type')
11+
12+
car = Vehicle()
13+
print(car)
14+
car.type()

OOP/P03_InstanceAttributes.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#In this example we will be seeing how instance Attributes are used
2+
#Instance attributes are accessed by: object.attribute
3+
#Attributes are looked First in the instance and THEN in the class
4+
5+
import random
6+
class Vehicle():
7+
#Class Methods/ Attributes
8+
def type(self):
9+
#NOTE: This is not a class attribute as the variable is binded to self. Hence it becomes
10+
#instance attribute
11+
self.randomValue = random.randint(1,10) #Setting the instance attribute
12+
13+
car = Vehicle()
14+
car.type() #Calling the class Method
15+
print(car.randomValue) #Calling the instance attribute

OOP/P04_InitConstructor.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#This example shows the use of __init__ constructor
2+
3+
class Vehicle():
4+
#__init__ is used to set values as soon as new object are created
5+
#__init__ is a keyword hence it has to be named like it is
6+
def __init__(self): #called automatically hence known as magic method
7+
print('Calling init')
8+
self.val = 0
9+
self.cost = 10000 #Setting the default value when the object is created
10+
11+
def incrementVehicle(self):
12+
self.val += 1
13+
14+
15+
car = Vehicle() #__init__ is called
16+
print('First obj value:',car.val)
17+
car.incrementVehicle()
18+
car.incrementVehicle()
19+
print('First obj value after incrementing:',car.val) #2
20+
21+
bike = Vehicle() #__init__ is called makes val 0 for this ANOTHER instance
22+
print('Second obj value:',bike.val)

OOP/P05_FirstProgramusingOOP.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#In this assignment we would see the use of OOP
2+
3+
class MaxSizeList(object):
4+
def __init__(self, value):
5+
self.myList = []
6+
self.value = value
7+
8+
def push(self, String):
9+
try:
10+
String = str(String)
11+
self.myList.append(String)
12+
except ValueError:
13+
print('You can only push strings!')
14+
15+
def getList(self):
16+
print(self.myList[-self.value:])
17+
18+
if __name__ == '__main__':
19+
a = MaxSizeList(3)
20+
b = MaxSizeList(1)
21+
22+
a.push('Hey')
23+
a.push('Hello')
24+
a.push('Hi')
25+
a.push('Let\'s')
26+
a.push('Go')
27+
28+
b.push('Hey')
29+
b.push('Hello')
30+
b.push('Hi')
31+
b.push('Let\'s')
32+
b.push('Go')
33+
34+
a.getList()
35+
b.getList()

OOP/P06_Inheritance.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#This program illustrates the concept of inheritance
2+
#Python looks up for method in following order: Instance attributes, class attributes and the
3+
#from the base class
4+
5+
class Data(object):
6+
def getData(self):
7+
print('In data!')
8+
9+
class Time(Data): #Inhertiting from Data class
10+
def getTime(self):
11+
print('In Time!')
12+
13+
if __name__ == '__main__':
14+
data = Data()
15+
time = Time()
16+
17+
data.getData()
18+
time.getTime()
19+
time.getData() #Inherted Data method

OOP/P07_MoreOnInheritance.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#This program illustrates the advanced concepts of inheritance
2+
#Python looks up for method in following order: Instance attributes, class attributes and the
3+
#from the base class
4+
#mro: Method Resolution order
5+
6+
class Data(object):
7+
def __init__(self, data):
8+
self.data = data
9+
10+
def getData(self):
11+
print('Data:',self.data)
12+
13+
class Time(Data): #Inhertiting from Data class
14+
def getTime(self):
15+
print('Time:',self.data)
16+
17+
if __name__ == '__main__':
18+
data = Data(10)
19+
time = Time(20) #inherited Class -> Value passed to __init__of Data (Base class)
20+
21+
time.getTime()
22+
data.getData()
23+
time.getData()
24+
25+
print(Time.mro())

OOP/P08_MultipleInheritence.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#This program shows the order in which the classes are accessed in case of multiple inheritance
2+
#Python uses DEPTH FIRST SEARCH algorithm for lookups
3+
4+
class A(object):
5+
def doThis(self):
6+
print('Doing this in A')
7+
8+
class B(A):
9+
pass
10+
11+
#If class C was also eing derived from A then the lookup order would be D,B,C,A
12+
class C(object):
13+
def doThis(self):
14+
print('Doing this in C')
15+
16+
class D(B, A):
17+
pass
18+
19+
if __name__ == '__main__':
20+
dObj = D()
21+
dObj.doThis() #A method gets called because order for lookup is D,B,A,C this is shown by function mro
22+
23+
print(D.mro())

Programs/P01_hello.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#This program prints the entered message
2+
3+
def justPrint(text):
4+
'''This function prints the text passed as argument to this function'''
5+
print(text)
6+
7+
if __name__ == '__main__':
8+
justPrint('Hello')

Programs/P02_VariableScope.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#This programs shows the rules for variable scope
2+
3+
# LEGB Rule: Local, Enclosing, Global, Built-in
4+
5+
x = 'Global x'
6+
7+
def test():
8+
#global x
9+
y = 'Local y'
10+
x = 'Local x'
11+
print(x +', '+ y) #prints 'Local x' and 'Local y'
12+
13+
if __name__ == '__main__':
14+
test()
15+
print(x) #prints 'Global x'

Programs/P03_ListsOperations.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#This program gives examples about various list operations
2+
3+
#Syntax: list[start: end: step]
4+
5+
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
6+
#index 0 1 2 3 4 5 6 7 8
7+
# -9 -8 -7 -6 -5 -4 -3 -2 -1
8+
9+
#List Slicing
10+
print('Original List:',myList)
11+
print('First Element:',myList[0]) #Prints the first element of the list or 0th element of the list
12+
print('Element at 2nd Index position:',myList[2]) #Prints the 2nd element of the list
13+
print('Elements from 0th Index to 4th Index:',myList[0: 5]) #Prints elements of the list from 0th index to 4th index. IT DOESN'T INCLUDE THE LAST INDEX
14+
print('Element at -7th Index:',myList[-7]) #Prints the -7th or 3rd element of the list
15+
16+
#To append an element to a list
17+
myList.append(10)
18+
print('Append:',myList)
19+
20+
#To find the index of a particular element
21+
print('Index of element \'6\':',myList.index(6)) #returns index of element '6'
22+
23+
#To sort the list
24+
myList.sort()
25+
26+
#To pop last element
27+
print('Poped Element:',myList.pop())
28+
29+
#To remove a particular element from the lsit BY NAME
30+
myList.remove(6)
31+
print('After removing \'6\':',myList)
32+
33+
#To insert an element at a specified Index
34+
myList.insert(5, 6)
35+
print('Inserting \'6\' at 5th index:',myList)
36+
37+
#To count number of occurences of a element in the list
38+
print('No of Occurences of \'1\':',myList.count(1))
39+
40+
#To extend a list that is insert multiple elemets at once at the end of the list
41+
myList.extend([11,0])
42+
print('Extending list:',myList)
43+
44+
#To reverse a list
45+
myList.reverse()
46+
print('Reversed list:',myList)

Programs/P10_LCM.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#This program calculates the LCM of the two numbers entered by the user
2+
3+
def LCM(number1, number2):
4+
'''This function calculates LCM of two numbers inputed by the user'''
5+
maximum = max(number1, number2)
6+
i = maximum
7+
while True:
8+
if (i % number1 == 0 and i % number2 == 0):
9+
lcm = i
10+
break
11+
i += maximum
12+
13+
return lcm
14+
15+
if __name__ == '__main__':
16+
userInput1 = int(input('Enter first number: '))
17+
userInput2 = int(input('Enter second number: '))
18+
print('LCM of {} and {} is {}'.format( userInput1, userInput2, LCM(userInput1, userInput2)))

Programs/P11_BinaryToDecimal.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#This program converts the given binary number to its decimal equivalent
2+
3+
def binaryToDecimal(binary):
4+
'''This function calculates the decimal equivalent to given binary number'''
5+
binary1 = binary
6+
decimal, i, n = 0, 0, 0
7+
while(binary != 0):
8+
dec = binary % 10
9+
decimal = decimal + dec * pow(2, i)
10+
binary = binary//10
11+
i += 1
12+
print('Decimal equivalent of {} is {}'.format(binary1, decimal))
13+
14+
if __name__ == '__main__':
15+
userInput = int(input('Enter the binary number to check its decimal equivalent: '))
16+
binaryToDecimal(userInput)

Programs/P12_DecimalToBinary.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#Program to convert decimal to its equivalent binary
2+
3+
def decimalToBinary(n):
4+
'''Function to print binary number for the input decimal using recursion'''
5+
if n > 1:
6+
decimalToBinary(n//2)
7+
print(n % 2,end = '')
8+
9+
if __name__ == '__main__':
10+
userInput = int(input('Enter the decimal number to find its binary equivalent: '))
11+
decimalToBinary(userInput)
12+
print()

Programs/P13_Palindrome.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#This program checks for the palindrome
2+
3+
def palindrome(string):
4+
'''This function checks the string for palindrome'''
5+
revString = string[::-1]
6+
if string == revString:
7+
print('String is Palindrome')
8+
else:
9+
print('String is not Palindrome')
10+
11+
if __name__ == '__main__':
12+
userInput = str(input('Enter a string to check for Palindrome: '))
13+
palindrome(userInput)

Programs/P14_CheckGreater.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#This prpgram checks that the given number is greater than all those numbers in th list
2+
3+
def checkGreater(number):
4+
'''This function checks whether the entered number is greater than those in the list'''
5+
original = [1,2,3,4,5]
6+
original.sort()
7+
if number > original[-1]:
8+
print('Yes, the entered number is greater than those in the list')
9+
else:
10+
print('No, entered number is less than those in the list')
11+
12+
if __name__ == '__main__':
13+
userInput = int(input('Enter the number to check: '))
14+
checkGreater(userInput)

Programs/P15_Arguments.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#This program gives a demo of how can you pass arguments while running python programs
2+
#Run the program as: python P15_Arguments.py Omkar Pathak
3+
4+
import sys
5+
6+
def arguments():
7+
'''This function prints the argruments passed while running the python program'''
8+
try:
9+
print('This is the name of the script:', sys.argv[0])
10+
print('First argument:', sys.argv[1])
11+
print('Second argument:', sys.argv[2])
12+
except IndexError:
13+
print('Give only two arguments')
14+
15+
if __name__ == '__main__':
16+
arguments()

Programs/P16_CountVowels.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#This program counts the vowels present in the user input
2+
3+
def countVowels(sentence):
4+
'''This function counts the vowels'''
5+
count = 0
6+
sentence = sentence.lower()
7+
for c in sentence:
8+
if c in ['a', 'e', 'i', 'o', 'u']:
9+
count += 1
10+
return count
11+
12+
13+
if __name__ == '__main__':
14+
userInput = str(input("Enter the string to check for vowels: "))
15+
count = countVowels(userInput)
16+
print('Vowel Count: ',count)

Programs/P17_EvenOdd.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#This program takes input from user and sorts the numbers in two arrays, one of even and other of odd
2+
3+
def evenOdd(numbers):
4+
'''This function divides the numbers in two arrays one of even and other of odd'''
5+
even = []
6+
odd = []
7+
for number in numbers:
8+
if int(number) % 2 == 0:
9+
even.append(number)
10+
else:
11+
odd.append(number)
12+
return even, odd
13+
14+
if __name__ == '__main__':
15+
userInput = input("Enter the numbers (space separated) to check: ")
16+
userInput = list(userInput.split())
17+
even, odd = evenOdd(userInput)
18+
print('Even Nos: ', ','.join(even), '\n', 'Odd Nos: ', ','.join(odd))

Programs/P18_Logging.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#This program illustrates a logging example
2+
import logging
3+
4+
def log(number):
5+
''' This function creates a log file if any error is reported '''
6+
logging.basicConfig(filename = 'P18-logfile.txt', level = logging.INFO)
7+
try:
8+
if int(number) % 2 == 0:
9+
print('Successful')
10+
else:
11+
print('Unsuccessful, this instance will be reported, check the log file')
12+
logging.info('Invalid Entry')
13+
except:
14+
print('Please enter a valid integer')
15+
16+
if __name__ == '__main__':
17+
try:
18+
userInput = int(input('Enter a number: '))
19+
log(userInput)
20+
except:
21+
print('Please enter a valid integer')

0 commit comments

Comments
 (0)