python easy introduction

------
print 'hello world'

------
for name in ('peter', 'paul', 'mary'):
print name

------
# This is a Python comment. \n is a newline
name = raw_input('What is your name?\n')
print 'Hi', name

------
parentRabbits, babyRabbits = (1, 1)
while babyRabbits < 100:
print 'This generation has %d rabbits' %
babyRabbits
parentRabbits, babyRabbits = (babyRabbits,
parentRabbits + babyRabbits)

------
# def defines a method in Python
def tax(itemCharge, taxRate = 0.05):
return itemCharge * taxRate
print '%.2f' % tax(11.35)
print '%.2f' % tax(40.00, 0.08)

------
import re
for test_string in [ '555-1212', 'ILL-EGAL']:
if re.match('\d\d\d-\d\d\d\d$', test_string):
print test_string, 'is a valid US local
phone number'
else:
print test_string, 'rejected'

------
prices = {'apple': 0.40, 'banana': 0.50}
myPurchase = {
'apple': 1,
'banana': 6}
groceryBill = sum([prices[fruit] *
myPurchase[fruit]
for fruit in myPurchase])
print 'I owe the grocer $%.2f' % groceryBill

------
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy('apple')
myCart.buy('banana')
print myCart.boughtItems()

------
# indent your Python code to put into an email
import glob
pythonFiles = glob.glob('*.py')
pythonFiles.sort()
for fn in pythonFiles:
print ' ------'
for line in open(fn):
print ' ' + line.rstrip()
print

------
import time
now = time.localtime()
hour = now.tm_hour
if hour < 8: print 'sleeping'
elif hour < 9: print 'commuting'
elif hour < 17: print 'working'
elif hour < 18: print 'commuting'
elif hour < 20: print 'eating'
elif hour < 22: print 'resting'
else: print 'sleeping'

No comments: