In [1]:
#singBirthday v1.0
def singBirthday():
print "Happy birthday to you"
print "Happy birthday to you"
print "Happy birthday dear Anelise"
print "Happy birthday to you"
singBirthday()
In [2]:
#singBirthday v2.0
def happy():
print "Happy birthday to you"
def singBirthday():
happy()
happy()
print "Happy birthday dear Anelise"
happy()
singBirthday()
In [3]:
#singBirthday v3.0
def happy():
print "Happy birthday to you"
def singBirthday(person):
happy()
happy()
print "Happy birthday dear "+person
happy()
def main():
singBirthday("Anelise")
print
singBirthday("Piers")
main()
In [6]:
## What's wrong with this code? How can we fix it?
def sumNumbers(first, second):
result = first + second
return result
def main():
first_num = 2
second_num = 4
final = sumNumbers(first_num, second_num)
print final
main()
In [ ]:
## pizzaArea.py
## This program calculates the cost per square inch of a pizza
import math
## Calculates the area of a pizza, given it's diameter
def pizzaArea(d):
r = float(d) / 2
pi = math.pi
square_inches = (r**2) * pi
return square_inches
## This function calculates cost per square inch
## Takes (square inches, cost) as arguments
## Returns cost per square inch
def squareInchCost(square_inches, cost):
total = float(cost)/square_inches
return total
### Diameter and cost are set in the main
def main():
diameter = 18.0
cost = 24.00
sq_inches = pizzaArea(diameter)
result = squareInchCost(sq_inches, cost)
print "You paid $%0.2f per square inch of pizza." %(result)
main()
In [8]:
##### Addint Interest 1.0
### This program demonstrates interest accumulation w/ an immutable type
## Adds interest rate to original balence
def addInterest(balance, rate):
newBalance = balance * (1 + rate)
balance = newBalance
return balance
## Tests function on a set amount and interest rate
def test():
amount = 1000
rate = 0.05
amount = addInterest(amount, rate)
print amount
test()
In [9]:
###### Adding Interest v2.0
###### Illustrates modification of a mutable parameter (list)
## Adds interest to original balances
## Note: This code is for a list of balances
def addInterest(balances, rate):
for i in range(len(balances)):
balances[i] = balances[i] * (1+rate)
## Tests code on a set list of balances and a set rate
def test():
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, 0.05)
print amounts
test()