python练习实例
#!/usr/bin/python # -*- coding: UTF-8 -*- try: fh = open("testfile","w") fh.write("testing") except Exception as e: print str(e) else: print 'sucessed' fh.close() def functionName(level): if level <2: raise Exception("Invalid level!",level) if __name__ == "__main__": functionName(1)
#............................................. class Networkerror(RuntimeError): def __init__(self,arg): self.args = arg try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args #........................................................ while True: reply = input('Enter text:') if reply == 'stop':break try: num = int(reply) except: print('bad' * 8) else: print (int(reply) * 2) print 'Bye' #................................................... import py_compile import sys file = raw_input("please enter your name") py_compile.compile(file) sys.exit() #................................................ #汉诺塔问题 def my_print(args): print args def move(n,a,b,c): my_print((a,'-->',c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c)) move(3,'a','b','c') #............................................................... fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print '当前水果:', fruits[index] print "Good bye!"
#............................................... #判断10 ~20的范围内质数和非质数 Prime = [] NoPrime = [] for num in range(10,20): for i in range(2,num): if num%i == 0: print '%d不是质数' % num NoPrime.append(num) break else: print '%d是质数' % num Prime.append(num) print '质数为:', Prime print '非指数为:', NoPrime #使用内置 enumerate 函数进行遍历: sequence = [12, 34, 34, 23, 45, 76, 89] for i,j in enumerate(sequence): print i,j #.............................................
#打印空心等边三角形 rows = int(raw_input('输入行数:')) for i in range(0, rows): for k in range(0, 2 * rows - 1): if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1): print " * ", elif i == rows - 1: if k % 2 == 0: print " * ", else: print " ", else: print " ", print "\n" #............................................ import os,sys ret = os.access('test/foo.txt',os.F_OK) print "F_OK - 返回值:%s" % ret ret = os.access('test/foo.txt',os.R_OK) print "R_OK - 返回值:%s" % ret ret = os.access('test/foo.txt',os.W_OK) print "W_OK - 返回值:%s" % ret ret = os.access('test/foo.txt',os.X_OK) print "X_OK - 返回值:%s" % ret #..........................................
import os, sys path = "test/" # 查看当前工作目录 retval = os.getcwd() print "当前工作目录为 %s" % retval # 修改当前工作目录 os.chdir( path ) # 查看修改后的工作目录 retval = os.getcwd() print "目录修改成功 %s" % retval #........................................
import os, sys dirPath = "test/" print '移除前test目录下有文件:%s' %os.listdir(dirPath) #判断文件是否存在 if(os.path.exists(dirPath+"foo.txt")): os.remove(dirPath+"foo.txt") print '移除后test 目录下有文件:%s' %os.listdir(dirPath) else: print "要删除的文件不存在!" #...................................................
import os,sys import shutil dstPath="test/" print "目录删除前: %s" % os.listdir(dstPath) #递归的删除目录及文件 #shutil.rmtree('test/aa') #以下两个函数用于删除空目录文件 os.rmdir("test/aa") #os.removedirs("test/aa") print "目录删除后: %s" % os.listdir(dstPath) #.................................................
class Employee: empCount = 0 def __init__(self,name,salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d " % Employee.empCount def displayEmployee(self): print "Name:" , self.name, ",Salary: ", self.salary emp1 = Employee("yuan", 3000) emp2 = Employee("qiang",4000) #添加属性 emp1.age = 7 emp2.age = 8 #删除对象emp1的属性 #del emp1.age emp1.displayEmployee() emp2.displayEmployee() print "Total emploeey %d" % Employee.empCount print "emp1 is %d years old" %emp1.age print "Employee.__doc__:",Employee.__doc__ print "Employee.__name__:",Employee.__name__ print "Employee.__module__:",Employee.__module__ print "Employee.__bases__:",Employee.__bases__ print "Employee.__dict__:",Employee.__dict__ #....................................................... #析构函数 class Point: def __init__(self,x = 0,y = 0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name ,"销毁" pt1 = Point() pt2 = pt1 pt3 = pt1 print id(pt1),id(pt2),id(pt3) #打印出对象的 #调用析构函数进行对象的销毁 del pt1 del pt2 del pt3 #................................................
class Parent: parentAttr = 100 def __init__(self): print "调用父类构造函数" def parentMethod(self): print "调用父类方法" def setAttr(self,attr): Parent.parentAttr = attr def getAttr(self): print "父类属性:",Parent.parentAttr def aa(self): print "调用父类aa" class Child(Parent): def __init__(self): print "调用子类构造函数" def childMethod(self): print "调用子类方法" def aa(self): print "调用子类aa" c = Child() #实例化子类 c.childMethod() c.parentMethod() c.setAttr(200) c.getAttr() c.aa() #...................................... #元素符重载 class Vector(): def __init__(self,a,b): self.a = a self.b = b def __str__(self): return 'Vector (%d,%d)' %(self.a,self.b) def __add__(self, other): return Vector(self.a +other.a,self.b+other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1+v2 #....................................................
class JustCounter: __secretCount = 0 #私有成员 publicCount = 0 #公有成员 def count(self): self.__secretCount += 1 self.publicCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.publicCount #print counter.__secretCount #报错,私有成员,不能通过对象进行访问 print counter._JustCounter__secretCount #可以通过object._className__attrName 这样组合的方式进行访问私有成员 #.............................................
#re成员函数match和search import re print (re.match("www","www.baidu.com").span()) print (re.match("baidu","www.baidu.com")) #........................................
import re line = "Cats are smarter than dogs" matchObj = re.search('dogs',line,re.M|re.I) if matchObj: print "search----matchObj.group(): ", matchObj.group() else: print "No match!" matchObj = re.match('dogs',line,re.M|re.I) if matchObj: print "match----matchObj.group(): ", matchObj.group() else: print "No match!" #......................................
import re phone = "2004-959-559 # 这是一个国外电话号码" # 删除字符串中的 Python注释 num = re.sub('#.*', "", phone) print "电话号码是: ", num # 删除非数字(-)的字符串 num = re.sub('\D', "", phone) print "电话号码是 : ", num #....................................................
import re def double(matched): value = int(matched.group('value')) print value return str(value*2) s = 'A223D23SSS#2E23236' print(re.sub('(?P<value>\d+)', double, s)) # 将匹配的数字乘于 2 def double(matched): value = int(matched.group('value')) return str(value * 2) s = 'A23G4HFD567' print(re.sub('(?P<value>\d+)', double, s)) #......................................
import thread import time def print_time(threadname,delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" %(threadname,time.ctime(time.time())) try: thread.start_new_thread(print_time,("Thread-1",2,)) thread.start_new_thread(print_time,("Thread-2",4,)) except: print "Error: unable to start thread" while 1: pass #..............................................
import threading import time exitFlag = 0 class myThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting" + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: print "退出线程" threading.Thread.exit() time.sleep(delay) print "%s: %s" % (threadName,time.ctime(time.time())) counter -=1 thread1 = myThread(1,"Thread-1", 1) thread2 = myThread(2,"Thread-2", 1) thread1.start() thread2.start() print "Exitting Main Thread" #...................................................... import threading import time class myThread(threading.Thread): def __init__(self,threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name threadLock.acquire() print_time(self.name, self.counter, 3) threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" %(threadName, time.ctime(time.time())) counter -= 1 threadLock = threading.Lock() threads = [] thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) thread1.start() thread2.start() threads.append(thread1) threads.append(thread2) for t in threads: t.join() print "Exiting Main Thread" #..........................................................
import Tkinter top = Tkinter.Tk() top.mainloop() #......................................................
from Tkinter import * root = Tk() li = ['C','python','php','html','SQL','java'] movie = ['CSS','jQuery','Bootstrap'] listb = Listbox(root) listb1 = Listbox(root) for item in li: listb.insert(0,item) for item in movie: listb1.insert(1,item) listb.pack() listb1.pack() root.mainloop() #.....................................................
#1,2,3,4组成多少种不同的三位数(个位,十位,百位数字各不相同) count = 0 for a in range(1,5): for b in range(1,5): for c in range(1,5): if a != b and a != c and b != c: count += 1 print a,b,c print "共%d种组合" %count #....................................................
while True: Profit = raw_input("请输入本月的利润:") if Profit.isdigit(): Profitint = int(Profit) if Profitint <=100000: bonus = Profitint * 0.1 elif Profitint > 100000 and Profitint < 200000: bonus = (Profitint - 100000) * 0.075 + 100000 *0.1 elif Profitint >= 200000 and Profitint < 400000: bonus = (Profitint - 200000) * 0.05 + 10000 +7500 elif Profitint >= 400000 and Profitint < 600000: bonus = (Profitint - 400000) * 0.03 + 10000 + 7500 + 10000 elif Profitint >= 600000 and Profitint < 1000000: bonus = (Profitint - 600000) * 0.015 + 10000 + 7500 + 10000+6000 else: bonus = (Profitint - 1000000) * 0.01 + 10000 + 7500 + 10000+6000 + 3000 print bonus elif Profit == 'q': exit(0) else: print "您输入的内容不合法!" #''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #判断输入的日期是一年种的第几天 print "please input Date:" while True: year = raw_input("year:") if year.isdigit() == 0: print "输入的年份不合法,请重新输入!" else: yearint = int(year) break while True: month = raw_input("month:") if month.isdigit() == 1: monthint = int(month) if 1<= monthint <=12: break else: print "输入的月份不合法,请重新输入!" continue else: print "输入的月份不合法,请重新输入!" continue while True: day = raw_input("day:") if month.isdigit() == 1: dayint = int(day) if dayint in (1,3,5,7,8,10,12): if 1<= dayint <=31: break else: print "输入的日期不合法,请重新输入!" continue elif dayint in (4,6,9,11): if 1<= dayint <=30: break else: print "输入的日期不合法,请重新输入!" continue else: if yearint%4 == 0 and yearint%100 != 0 or yearint%400 ==0: if 1<= dayint <= 29: break else: print "输入的日期不合法,请重新输入!" continue else: if 1 <= dayint <= 28: break else: print "输入的日期不合法,请重新输入!" continue else: print "输入的日期不合法,请重新输入!" continue if yearint%4 == 0 and yearint%100 != 0 or yearint%400 ==0: totalday= [31,60,91,121,152,182,213,244,274,305,335,366] else: totalday = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] if int(month) == 1: days = dayint else: days = totalday[int(month)-2] + dayint print "这是今年的第 %d 天" % days #..........................................................
#排序
l =[] for i in range(1,4): x = int(raw_input('integer:')) l.append(x) l.sort() print l #...............................................
# 使用递归 def fib(n): if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) # 输出了第10个斐波那契数列 print fib(10) #................................................. a = [1,2,3,4,5] b = [] for i in range(0,len(a)): b.append(a[i]) print b ''' #乘法口诀 ''' for i in range(1,10): for j in range(1,i+1): print "%d*%d=%d" %(i,j,i*j), print #.................................................
import time myD = {1:'a',2:'b'} for key,value in dict.items(myD): print key,value time.sleep(1) #......................................................
import time print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) time.sleep(1) print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) #......................................................
f1 = 1 f2 = 1 for i in range(1,22): print "%14ld %14ld" %(f1,f2), if(i % 3) == 0: print " " f1 = f1+f2 f2 = f1+f2 #................................................................
flag = 0 count = 0 for i in range(101,200): for j in range(2,i): if i % j == 0: flag = 1 if flag == 0: print i count +=1 else: flag = 0 print "total :%d " %count #.......................................................
for a in range(1,10): for b in range(0,10): for c in range(0,10): if a**3 + b**3 + c**3 == c +b*10+a*100: print c +b*10+a*100 #...............................................
import datetime if __name__ == "__main__": print(datetime.date.today().strftime('%d/%m/%Y')) time1 = datetime.date(1941,1,5) print(time1.strftime('%d/%m/%Y')) #在time1的时间上加一天 time2 = time1 + datetime.timedelta(days=1) print(time2.strftime("%d/%m/%Y")) time3 = time2.replace(month=time2.month+1) print(time3.strftime('%d/%m/%Y')) #..........................................................
#计算输入字串中英文字母,空格,数字和其他字符的个数 alphacount = 0 digitcount = 0 spacecount = 0 elsecount = 0 string = raw_input("please input string:") for s in string: if s.isdigit(): digitcount += 1 elif s.isalpha(): alphacount += 1 elif s.isspace(): spacecount += 1 else: elsecount += 1 print "数字字符共%d个" % digitcount print "字母字符共%d个" % alphacount print "空字符共%d个" % spacecount print "其他字符共%d个" % elsecount #...................................................
num = int(raw_input("please input the number:")) amount = int(raw_input("please input the amount:")) total = 0 num1 = 0 for i in range(0,amount): num1 += num*(10**i) total = total + num1 print num1 print total #.................................................................
#一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。 total = 0 a = [] for num in range(2,1001): for i in range(1,num): if num % i == 0: total = total + i a.append(i) if total == num: print total print a total = 0 a = [] #.............................................
num = 1 for i in range(1,10): num = num*2+2 print num #....................................................
for a in ['x','y','z']: for b in ['x', 'y', 'z']: for c in ['x', 'y', 'z']: if(a!=b)and(b!=c)and(c!=a) and (a!='x') and (c!='x') and (c!='z'): print 'a和%s比赛,b和%s比赛,c和%s比赛' %(a,b,c) #...........................................................
a1 = 2.0 a2 = 3.0 b1 = 1.0 b2 = 2.0 total = 0.0 for i in range(1,20): if i == 1: total = total + a1/b1+a2/b2 else: temp = a1 + a2 a1 = a2 a2 = temp temp = b1 + b2 b1 = b2 b2 = temp total = total + a2 / b2 print total #......................................... #翻转字串输出 def Reverse(str,len): if len == 0: return print str[len-1], len = len -1 Reverse(str,len) string = raw_input("please input string:") len = len(string) Reverse(string,len) #........................................................
def Age(n): if n == 1: return 10 else: return Age(n-1)+2 print Age(5) #..........................................
num = int(raw_input("number:")) count = 0 n = num while True: a = n%10 print a, count += 1 n = n/10 if n == 0: break print "此数是%d位数" % count #..................................................
#判断输入的数字是否为回文数 num = raw_input("number:") lenth = len(num) flag = True for i in range(lenth/2+1): if num[i] != num [lenth-i-1]: flag = False if flag == False: print "%d不是回文数" % int(num) else: print "%d是回文数" % int(num) #......................................................
Firstletter = raw_input("week:") if Firstletter == "s" or Firstletter == "S": Secondletter = raw_input("please input the second letter:") if Secondletter == "u": print "today is sunday!" elif Secondletter == "a": print "today is saturday!" else: print "data error!" elif Firstletter == "m" or Firstletter == "M": print "totay is monday!" elif Firstletter == "T" or Firstletter == "t": Secondletter = raw_input("please input the second letter:") if Secondletter == "u": print "today is Tuesday!" elif Secondletter == "h": print "today is Thursday!" else: print "data error!" elif Firstletter == "W" or Firstletter == "w": print "today is Wednesday!" elif Firstletter == "F" or Firstletter == "f": print "today is Friday!" else: print "data error!" #...................................................
#倒序输出列表元素
a = ['one', 'two', 'three'] for i in a[::-1]: print i ''' ''' def export(): L = [1,2,3,4,5] s1 = ','.join(str(n) for n in L) print s1 if __name__ == "__main__": export() #..................................................... #设置文本颜色 class bcolors: HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[91m" WARNING = "\033[93m" FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' print bcolors.OKGREEN + "警告的颜色字体" + bcolors.ENDC #.......................................................
#二维数组 if __name__ == "__main__": a = [] sum = 0.0 for i in range(3): a.append([]) #列表里面包含列表形成二维数组 for j in range(3): a[i].append(float(raw_input("input num:\n"))) for i in range(3): sum += a[i][i] print sum #输出二维数组 for i in range(3): print a[i] #..........................................................
#给已经排序的列表中插入新的元素 num = int(raw_input("number:")) a = [1,3,4,5,12,13,23,34,45,56,0]#最后一个0作为占位符,以防止列表插入一个元素时越界 lenth = len(a)-1 if num >=a[lenth -1]: a[lenth] = num else: for i in range(lenth): if num < a[lenth-i-1]: a[lenth-i] = a[lenth-i-1] a[lenth-i-1] = num print a
#...........................................................
a = [1,2,3,4,5] lenth = len(a) for i in range(lenth): print a[lenth-i-1] ''' ''' X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] total = [[0,0,0], [0,0,0], [0,0,0]] for i in range(3): for j in range(3): total[i][j] = X[i][j] + Y[i][j] for i in range(3): print total[i] #.................................................
MAXIMUM = lambda x,y : (x>y)*x + (x<y)*y MINMUM = lambda x,y:(x>y)*x + (x<y)*x if __name__ == '__main__': a = 10 b = 20 print "The largar one is %d " % MAXIMUM(a,b) print "The lower one is %d" % MINMUM(a,b)
#.................................................. if __name__ == "__main__": from Tkinter import * canvas = Canvas(width =800,height = 600,bg = "yellow") canvas.pack(expand= YES,fill=BOTH) k = 1 j = 1 for i in range(0,26): canvas.create_oval(310-k,250-k,310+k,250+k,width=1) k += j j += 0.3 mainloop() #......................................................
if __name__ == '__main__': import turtle turtle.title("画圆") while True: turtle.setup(800,800,100,100) pen=turtle.Turtle() pen.color("blue") pen.width(5) pen.shape("turtle") pen.speed(1) pen.circle(100) #.........................................................
#画直线 if __name__ == "__main__": from Tkinter import * canvas = Canvas(width=300, height=300,bg = "green") canvas.pack(expand=YES,fill=BOTH) x0 = 263 y0 = 263 y1 = 275 x1 = 275 for i in range(19): canvas.create_line(x0,y0,x0,y1,width=1, fill='red') x0 = x0 - 5 y0 = y0 - 5 x1 = x1 + 5 y1 = y1 + 5 x0 = 263 y1 = 275 y0 = 263 for i in range(21): canvas.create_line(x0,y0,x0,y1,fill='red') x0 += 5 y0 += 5 y1 += 5 mainloop() #......................................................................
#画正方形 if __name__ == "__main__": from Tkinter import * root = Tk() root.title('Canvas') canvas = Canvas(root,width = 400,height = 400,bg = "yellow") x0 = 263 y0 = 263 y1 = 275 x1 = 275 for i in range(19): canvas.create_rectangle(x0,y0,x1,y1) x0 -= 5 y0 -= 5 x1 += 5 y1 += 5 canvas.pack() root.mainloop() #................................................................ #画椭圆 if __name__ == "__main__": from Tkinter import * x = 360 y = 160 top = y -30 bottom = y -30 canvas = Canvas(width = 400,height = 600,bg = 'white') for i in range(20): canvas.create_oval(250-top,250 - bottom,250+top,250+bottom) top -= 5 bottom += 5 canvas.pack() mainloop() #.....................................................................
import math class PTS: def __init__(self): self.x = 0 self.y = 0 points = [] def LineToDemo(): from Tkinter import * screenx = 400 screeny = 400 canvas = Canvas(width = screenx,height = screeny,bg = 'white') AspectRatio = 0.85 MAXPTS = 15 h = screeny w = screenx xcenter = w / 2 ycenter = h / 2 radius = (h - 30) / (AspectRatio * 2) - 20 step = 360 / MAXPTS angle = 0.0 for i in range(MAXPTS): rads = angle * math.pi / 180.0 p = PTS() p.x = xcenter + int(math.cos(rads) * radius) p.y = ycenter - int(math.sin(rads) * radius * AspectRatio) angle += step points.append(p) canvas.create_oval(xcenter - radius,ycenter - radius, xcenter + radius,ycenter + radius) for i in range(MAXPTS): for j in range(i,MAXPTS): canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y) canvas.pack() mainloop() if __name__ == '__main__': LineToDemo() #....................................................
def Maxnum(n,lenth): max = n[0] for i in range(lenth): if n[i] > max: max = n[i] index = i return index def Minnum(n,lenth): min = n[0] for i in range(lenth): if n[i] < min: min = n[i] index = i return index if __name__ == "__main__": a = [] for i in range(5): num = int(raw_input("number:")) a.append(num) print a lenth = len(a) maxindex = Maxnum(a,lenth) minindex = Minnum(a,lenth) a[0],a[maxindex] = a[maxindex],a[0] a[lenth-1],a[minindex] = a[minindex],a[lenth-1] print a #.........................................................
from collections import deque m = 3 a = [1,2,3,4,5,6,7] #7 个数 f = deque(a) f.rotate(m) print list(f) #.....................................................
if __name__ == "__main__": a = [1,3,2] b = [3,4,5] a.sort() print a print a + b a.extend(b) #连接两个列表 print a #...................................................... num = int(raw_input("number:")) sum = 0.0 for i in range(1,num+1): if num%2 == 0 and i%2 == 0: sum = sum + 1.0/i elif num%2 != 0 and i%2 != 0: sum = sum + 1.0/i print sum #............................................................
if __name__ == "__main__": person = {"li":18,"wang":13,"zhang":20,"sun":30} m = 'li' for key in person.keys(): if person[m] < person[key]: m = key print "%s,%d" %(m,person[m]) #..........................................................
if __name__ == '__main__': str1 = raw_input('input string:\n') str2 = raw_input('input string:\n') str3 = raw_input('input string:\n') print str1, str2, str3 if str1 > str2: str1, str2 = str2, str1 if str1 > str3: str1, str3 = str3, str1 if str2 > str3: str2, str3 = str3, str2 print 'after being sorted.' print str1, str2, str3 #..................................................... my_lambda = lambda arg:arg+1 result = my_lambda(2) print result