1: Overview of Data Structures and Algorithms¶

Example 1: Page 20¶

In [1]:
class Thermostat:
"""A simple thermostat class"""
#since private instance variables don't exist in Python,
#hence using a convention: name prefixed with an underscore, to treat them as non-public part
def __init__(self):
self._currentTemp = 0.0
self._desiredTemp = 0.0

def furnace_on(self):
#method body goes here
pass

def furnace_off(self):
#method body goes here
pass
#end class Thermostat


Example 2: Page 22¶

In [2]:
#demonstrates basic OOP syntax

class BankAccount:
"""A simple bank account class"""

def __init__(self, openingBalance):	#special method to create objects
#with instances customized to a specific initial state

#since private instance variables don't exist in Python,
#hence using a convention: name prefixed with an underscore, to treat them as non-public part
self._balance = openingBalance	#account balance

def deposit(self, amount):	#makes deposit
self._balance = self._balance + amount

def withdraw(self, amount):	#makes withdrawl
self._balance = self._balance - amount

def display(self):	#displays balance
print 'Balance=', self._balance
#end class BankAccount

ba1 = BankAccount(100.00)	#create account

print 'Before transactions, ',
ba1.display()	#display balance

ba1.deposit(74.35)	#make deposit
ba1.withdraw(20.00)	#make withdrawl

print 'After transactions, ',
ba1.display()	#display balance
#end

Before transactions,  Balance= 100.0
After transactions,  Balance= 154.35


Example 3: Page 25¶

In [3]:
#creating string objects
str1 = ''
str2 = 'George'

#verifying results
print str1
print str2

#naming string object
str3 = 'amanuensis'

#verifying results
print str3

#accessing specific characters from string using [] operator
ch1 = str2[3]

#verifying results
print ch1

#finding and printing number of characters in a string
print len(str1)

George
amanuensis
r
0