External Exam Download Resources Web Applications Games Recycle Bin

python 2


  1. functions
  2. recursion
  3. simpleArray
  4. multiDimensionalArray
  5. simpleClass
  6. inheritance

functions
def getAge():
    return int(input("how old r u?"))

def under18(currentAge):
    if(currentAge < 18):
        return True
    else:
        return False

myAge = getAge()
if under18(myAge):
    print("you are under 18")
else:
    print("you are 18 or older")

    
    

balance = 100

def deposit(amt):
    global balance
    balance += amt

deposit(15)
print(balance)

        
        

recursion
Recursion: solving a problem with a method that calls itself.
intRate = 0.05

def compound(amt, termsRemaining):
    if(termsRemaining == 0):
        return amt
    else:
        termsRemaining = termsRemaining - 1
        newamt = amt + (amt*intRate)
        return compound(newamt, termsRemaining)

print(compound(100,2))

        
        

simpleArray
a = [999,2,3]
a[0] = 1

print(a[2]) #prints '3'
print(len(a)) #prints '3', because there are 3 elements

for stuff in a:
   print("value:", stuff)

#using range to parse list via index:
for index in range(0,len(a)): #index will parse element 0, 1 & 2
   print("element: " + str(index) + ", value: " + str(a[index]))

   
   

multiDimensionalArray
note - there aren't multidimensional arrays as such in Python, what you have is a list containing other lists:
#jagged:
lists = [[10, 20], [30, 40, 50, 60, 70]]
for eachList in lists:
    print(eachList, len(eachList))

'''--------------
nested lists:
use a 'comprehension', which is 'an
expr that specifies a seq of vals'
--------------'''

singleList =["~" for i in range(3)]
#^3 "~" characters in a single list

nestedList =[["~" for x in range(3)] for y in range(3)]
#^3x3 grid of character "~"

nestedList[0][2] = "miss"
nestedList[1][0] = "hit"

for row in nestedList:
    print(row)

    
    

simpleClass
OOP = programming paradigm. some defns:
class Card:
    deckCounter = 0

    def __init__(self, title, suit):
        self.title = title
        self.suit = suit
        Card.deckCounter += 1

    def flipCard(self):
        print(self.title, "of", self.suit)

card1 = Card("Ace", "Spades")
card2 = Card("Seven", "Diamonds")

card1.flipCard()
card2.flipCard()
print(Card.deckCounter, "cards in deck")

    
    

inheritance
...and overriding parent class methods:
class Card:
    deckCounter = 0

    def __init__(self, title, suit):
        self.title = title
        self.suit = suit
        Card.deckCounter += 1

    def flipCard(self):
        print(self.title, "of", self.suit)

class Joker(Card):
    def __init__(self):
        Card.deckCounter += 1

    def flipCard(self):
        print("Joker")

card1 = Card("Ace", "Spades")
card2 = Card("Seven", "Diamonds")
card3 = Joker()

card1.flipCard()
card2.flipCard()
card3.flipCard()

print(Card.deckCounter, "cards in deck")