# -*- coding: cp936 -*- """ import random def rollDice(): die1 = random.randrange( 1, 7) die2 = random.randrange( 1, 7) workSum = die1 + die2 print "player rolled %d + %d = %d" % ( die1, die2, workSum ) return workSum sum = rollDice() if sum == 7 or sum == 11: Status = "WON" elif sum == 2 or sum == 3 or sum == 12: Status = "LOST" else: Status = "CONTINUE" myPoint = sum print "Point is", myPoint while Status == "CONTINUE": sum = rollDice() if sum == myPoint: Status = "WON" elif sum == 7: Status = "LOST" if Status == "WON": print "Player wins" else: print "Player loses" """ """ # 使用列表 ,最后输出,加上-,可以使名称左对齐 values = [] print "enter 10 integers;" for i in range( 10 ): newValue = int( raw_input("enter integer %d:" % ( i + 1 ))) values +=[ newValue ] print "\nCreating a histogram from values:" print "%s %10s %10s" % ("element", "value", "histogram") for i in range( len( values )): print "%7d %10d %s" % ( i, values[ i ], "*"*values[ i ]) """ """ # 使用元祖,元祖有数个逗号分隔的值组成,一个元组由数个逗号分隔的值组成,例如:t = 12345, 54321, 'hello!',元组在输出时总是有括号的,以便于正确表达嵌套结构 hour = int( raw_input( "enter hour:" ) ) minute = int( raw_input( "enter minute: " ) ) second = int ( raw_input ( "enter second:") ) currentTime = hour, minute, second print "the value of currentTime is:", currentTime print "The number of seconds since midnight is", currentTime[ 0 ]*3600 + currentTime[ i ] * 60 + currentTime[ 2 ] """ """ # 字符串,列表,元祖解包,表达方式一个是括号,一个是中括号???? aString = "abc" aList = [ 1, 2, 3 ] aTuple = "a", "A", 1 print "unpacking string..." first, second, third = aString print "String values:", first, second, third print "\nUnpacking list..." first, second, third = aList print "List values:", first, second, third print "\nUnpacking tuple..." first, second, third = aTuple print "Tuple values:", first, second, third x = 3 y = 4 print "\n Before x = %d, y = %d " % ( x, y) x, y = y, x print "after x = %d, y = %d " % ( x, y ) """ """ #序列切片 sliceString = "abcdefghij" sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sliceList = [ "s", "ss", "sss", "f", "ff", "fff", "ffff", "m", "mm", "mmm"] print "sliceString: ", sliceString print "sliceTuple: ", sliceTuple print "sliceList: ", sliceList print ###得到切片 当下标为负值的时候,结果不同于正数,我猜测,倒着数,没有0的概念,从-1开始的。。。??? start = int( raw_input ("enter start: ") ) end = int( raw_input ("enter end: ") ) print "\nsliceString[", start, ":", end, "] = ", \ sliceString[ start:end ] print "\nsliceTuple[", start, ":", end, "] = ", \ sliceTuple[ start:end ] print "\nsliceList[", start, ":", end, "] = ", \ sliceList[ start:end ] """ """ #字典## key, value, items/// #深拷贝,意味着独立性的拥有,不随原来的改动而改动! emptyDictionary = {} print "the value of emptyDictionary is:", emptyDictionary grades = { "John": 87, "Steve": 42, "Lau": 92, "Edwin": 89 } print "\nAll grades:", grades print "old one", grades[ "Steve" ] grades[ "Steve" ] = 90 print "new one", grades[ "Steve" ] del grades[ "John" ] print "after delete:", grades """ """ # list 三个内置函数map---逐个执行,filter---返回过滤,reduce---第一个和下一个,以此类推??? def f(x): return x % 2 !=0 and x % 3 != 0 print "the result is", filter(f, range(2, 25)) print map(f,range(2, 25)) def cube(x): return x*x print map(cube, range(1, 11)) print filter(cube, range(1, 11)) def add(x,y): return x+y print reduce(add, range(1, 11)) """ """ # 链表推导式 vec = [2, 4, 6] print [3*x for x in vec] """ """ # set无序不重合,测试,消除重复元素,支持联合,交集,差,对称差 basket = ['apple', 'orange', 'orange'] print set(basket) a = set('abcabcde') b = set('aeraey') print a,b print a - b print a & b """ """ # 查询学生的成绩 student = { "John": 60, "Steve": 42, "Lau": 92, "Edwin": 89 } x = 3 def check(): global x if x <= 0: print "您已经超过了最大极限,终止程序!" while (x > 0): name = raw_input ("请输入要查询的学生名字: ") whether = False print student.keys() for i in student.keys(): if student.has_key(name): whether = True break if whether == False: print "没有这个学生,请重新输入:" x = x-1 print "这是第", 3-x, "次查询" check() else: print student[name] break """ """ # 输入和输出,居中,靠右,靠左 import math x = 10 * 3.25 y = 200 * 200 s = 'the value of x is ' + repr(x) +', and y is ' + repr(y) + '...' print s print repr((x, y, ('spam', 'eggs'))) print (x, y, ('spam', 'eggs')) for x in range(1, 11): print repr(x).rjust(1), repr(x*x).rjust(2), print repr(x*x*x).rjust(10) string1 = "now i am here." print string1.rjust(20)[:7] # ??? print string1.ljust(20) print '-3.14'.zfill(7) print 'the value of PI is %5.3f ' % math.pi table = {'Sjoerd': 212, 'Jack': 334, 'Dcab': 6456} for name, phone in table.items(): print '%-10s ==> %10d' % (name, phone) """ """ # 读写文件----只能建立文件,不能读出空字符串 ????? import sys try: f = open('f.txt','w') print f f.read() f.write('this is a test') f.readline() except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror) # else 出现在所有except子句之后,当try语句没有抛出异常时,需要执行一些代码,可以使用这个语句 for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() """ """ # 定义类 class class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print x.r, x.i """ """ # 类的继承 class B: pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "d" except C: print "c" except B: print "b" """ """ # iter() 迭代器 s = 'abc' it = iter(s) print it.next(), it.next(), it.next() class Reverse: def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] for char in Reverse('spam'): print char """ # 生成器Generator,----yield data[index] def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] for char in reverse('golf'): print char # 生成器表达式 Generator Expressions xx = [10, 20, 30] yy = [7, 5, 3] print sum(x*y for x,y in zip(xx, yy)) from math import pi, sin sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91)) print sine_table # unique_words = set (word for line in page for word in line.split()) # print unique_words # grades = { "John": 87, "Steve": 42, "Lau": 92, "Edwin": 89 } # valedictorian = max((student.key, student.value) for student in grades) # print valedictorian data = 'golf' print list(data[i] for i in range(len(data)-1, -1, -1))
类对象
""" # 类的定义及其实现Time() class Time: def __init__( self ): # def __init__( self, hour = 0, minute = 0, second = 0 ) self._hour = 0 self._minute = 0 self._second = 0 # self.setTime(hour, minute, second ) def setTime( self, hour, minute, second ): self.setHour( hour ) self.setMinute( minute ) self.setSecond( second ) def setHour(self, hour ): if 0 <= hour < 24: self._hour = hour else: raise ValueError, "Invalid hour value:%d" % hour def setMinute(self, minute ): if 0 <= hour < 60: self._minute = minute else: raise ValueError, "Invalid minute value:%d" % minute def setSecond(self, second ): if 0 <= hour < 60: self._second = second else: raise ValueError, "Invalid second value:%d" % second def getHour( self ): return self._hour def getMinute( self ): return self._minute def getSecond( self ): return self._second def printMilitary( self ): print "% .2d:%.2d:%.2d" % \ ( self.hour, self.minute, self.second ), def printStandard( self ): standardTime = "" if self.hour == 0 or self.hour == 12: standardTime += "12:" else: standardTime += "%d:" % (self.hour % 12) standardTime += "%.2d:%.2d" % ( self.minute, self.second ) if self.hour < 12: standardTime += " AM" else: standardTime += " PM" print standardTime from Timel import Time time1 = Time() print "\nCalling method printMilitary:", time1.printMilitary() print "\nCalling method printStandard:", time1.printStandard() time1.hour = 25 time1.minute = 30 time1.second = 19 print "after alteration:", time1.printStandard(),time1.printMilitary() print Time.__module__,"-----", Time.__dict__ # 私有成员 class PrivateClass: def __init__(self): self.publicData = "public" self.__privateData = "private" x = PrivateClass() print x.publicData,x._PrivateClass__privateData # 类的调用 ----str字符串 class Employee: count = 0 def __init__(self, first, last): self.firstName = first self.lastName = last Employee.count += 1 print "Employee for %s, %s" \ %( self.lastName, self.firstName) def __str__(self): return "%s---%s" % \ ( self.firstName, self.lastName ) def __del__( self ): Employee.count -= 1 print "Employee for %s,%s" \ % (self.lastName, self.firstName) e1 = Employee("s", "baker") e2 = Employee("r", "jone") e3 = Employee("x", "hen") print e1 print e1.count del e1 del e2 """ # 继承 class Point: def __init__(self, xValue = 0, yValue = 0): self.x = xValue self.y = yValue def __str__(self): return "(%d, %d)" % (self.x, self.y) def main(): point =Point(72, 115) print "coordinate is ", point.x, point.y if __name__ == "__main__": main() import math class Circle( Point ): def __init__( self, x = 0, y = 0, radiusValue = 0.0 ): Point.__init__(self, x, y) self.radius = float ( radiusValue) def area( self ): return math.pi * self.radius ** 2 def __str__(self): return "center--%s radius--%f" % \ ( Point.__str__(self), self.radius ) def main(): circle = Circle(22,33,2) print "coordinate is ", circle.x, circle.y print "the area is %.2f" % circle.area() if __name__ == "__main__": main()
标准库
# 当前路径 import os print os.getcwd() # glob从目录通配符中搜索生成文件列表 import glob print glob.glob('*.py') #复制,移动---把第一个复制一份,名字为第二个 import shutil shutil.copyfile('module.py', 'x.py') # 正则匹配******强大的体现*** import re print re.findall(r'\bf[a-z]*', 'food is future') print re.sub(r'(\b[a-z])\1', r'\1', 'cat in the hat') # 测试 def average(values): print average([20, 30, 70]) import doctest print doctest.testmod()