| |
comp.lang.python |
I've always thought that the best way to introduce new When you go to the tutorial, though, you have to wade Below is my attempt at generating ten fairly simple, It was an interesting exercise. I constrained myself It was harder to show classes, and my ShoppingCart Anyway, here goes: ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ___________________________________________________________________________ _________
programmers to Python is to show them small code
examples.
through quite a bit of English before seeing any
Python examples.
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.
to ten lines or less, and it was pretty easy to
incorporate loops, conditionals, print, open(), lists,
tuples, dictionaries, and imported modules.
class is nothing more than an encapsulation of a list,
which has dubious value (although it's the start of
something more useful).
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'
Expecting? Get great news right away with email Auto-Check.
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html