0、猜数字
#-*-encoding:UTF-8-*-
import random
guess_number=random.randint(0,9)
loop_times=0
while loop_times<5:
print loop_times
try:
user_input_number=int(raw_input("请输入一个整数,范围0-99:".decode('utf-8').encode('gbk')))
except Exception,e:
print u"非法输入数据,必须输入整数"
continue
if user_input_number print u"猜小了" elif user_input_number>guess_number: print u"猜大了" else: print u"猜中了,您中奖了" loop_times +=1 if loop_times==5: #下面这行会报错,因为这里会掉用系统默认字符集(ascii)进行先解码然后再编码到gbk,ascii不能解码中文 #print "您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #下面这行可以,用utf-8来解码就可以 #print "您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行会报错,因为不能对中文的uinicode进行解码 #print u"您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行可以,有中文的unicode直接编码成gbk,可以正常显示 #print u"您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number break import sys reload(sys) sys.setdefaultencoding("utf-8") ''' letters="" for i in range(26): letters=letters+chr(90-i) print letters ''' ''' letters = "" for i in range(0,26,2): letters += chr(i+65) print letters ''' ''' #translate from abcd...-->fghi.., z->e letters=raw_input("input the letters:") #print letters #print len(letters) transletter = "" for i in letters: if (ord(i)+5) < 122: print"ord(i)+5 <122" transletter+=chr(ord(i)+5) else: print"ord(i)+5>=122" transletter+=chr(ord(i)+5-26) print ("jiamihou",transletter) untransletter ="" for i in transletter: if (ord(i))<102: untransletter += chr(ord(i)-5+26) else: untransletter+= chr(ord(i)-5) print (("解码后").decode("utf-8" ), untransletter) 例题: 如果算出一个十进制数对应的二进制数: 中文算法: 自己写的: decimalism = input("input number:") binary='' while (decimalism != 0): if decimalism %2 ==0: print "decimalism %2 =0" binary += "0" print "binary:", binary decimalism /=2 print "decimalism: ", decimalism else: print "decimalism %2 =1" binary += "1" print binary decimalism /=2 print "decimalism: ", decimalism print binary[::-1] 优化之后: decimalism = input("input number:") binary="" while (decimalism != 0): binary += str(decimalism %2) decimalism /=2 print "binary:",binary[::-1] 吴老写的: number = int(raw_input("input a number:")) bin_list=[] while 1: quient=number/2 bin_list.append(str(number%2)) number=quient if number==0: break print "result:","".join(bin_list[::-1]) --------------------------------------------------------------------------------------------------------------------------------- >>> a =1 >>> isinstance(a,int) True >>> b=1L >>> isinstance(b,long) True >>> c=1+1j >>> isinstance(c,complex) True >>> d = u"a" >>> isinstance(d,unicode) True >>> e="abc" >>> isinstance(e,str) True >>> f =[1] >>> isinstance(f,list) True >>> g=(1,2) >>> isinstance(g,tuple) True >>> h ={1:2} >>> isinstance(h,dict) True >>> instance(P,type) Traceback (most recent call last): File " NameError: name 'instance' is not defined >>> isinstance(P,type) True Print 5%2 =1 Import math dir(math) Math.sqrt(4) = 2 #-*-coding:UTF-8-*- fp1 = open('d:\\testfile.txt', 'r')#手工创建文件为ANSI编码保存(gbk) info1 = fp1.read() #已知是GBK编码,解码成Unicode tmp = info1.decode('GBK') fp2 = open('d:\\testfile2.txt','w') #编码成UFT-8编码的str info2= tmp.encode('UTF-8') fp2.write(info2)#写入uft8字符,并进行保存 fp2.close() #文件会变成utf-8编码保存 test1是ANSI (GBK)编码 test2是UTF编码 #-*_ coding:UTF-8-*- s= "byte string" print type(s) #str to unicode u = s.decode() u=s.decode() print type(u) #unicode to str backToBytes=u.encode() print type(backToBytes) #获取系统编码示例: #-*-coding:UTF-8-*- import sys print sys.getdefaultencoding() #更改系统编码代码示例: #-*-coding:UTF-8-*- import sys reload(sys) sys.setdefaultencoding('UTF-8') #-*- coding: UTF-8 -*- import sys reload(sys) #去掉此行和下行,则程序出错 sys.setdefaultencoding('UTF-8') print sys.getdefaultencoding() print type(u"我") print type(u"我".encode('utf-8')) print type(u"我".decode('utf-8')) #”我”是str类型,encode前,python自动用默认编码进行decode为unicode类型,默认为ascii,则无法decode print “我”.encode(‘utf-8’).decode(‘utf-8’) #会调用默认的编码进行decode在进行encode(‘utf-8’) 注意:这里在“我”之前没有用u,所以“我”是字节型字符串,而且后边没有先decode(),不会直接编码为uft-8(需要unicode才可以),所以系统默认调用decode(utf-8)来解码为unicode,然后再编码为后边的 utf-8(encode(‘utf-8’).。。。),如果没有制定系统默认编码为uft-8,则系统默认的编码为ascii,这里系统自动调用decode(ascii)则会报错,因为ascii不会解码中文. http://www.cnblogs.com/guosq/p/6378639.html 大了提示猜小点,小了提示猜大点,5次为限,猜中了提示中奖了,然后推出 #-*-encoding:UTF-8-*- a = 98 for i in range(5): print i input_number=input("please guess the number:") if input_number >a: print("please guess smaller") elif input_number print("please guess bigger") else: print("you got it, please get your award!!") exit() if i == 4: print("you have tried 5 times,the number is:", a) #-*-encoding:UTF-8-*- ''' import sys reload(sys) print sys.getdefaultencoding() sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() ''' a = 98 for i in range(5): print i input_number=input(u"请输入一个数:".encode('gbk')) if input_number >a: print(u"请猜小一点!") elif input_number print(u"请猜大一点1") else: print(u"猜中了,您中大奖了!!") exit() if i == 4: print u"您试了5次了,没有机会了,数字是:".encode('gbk'), a #-*-encoding:UTF-8-*- import random guess_number=random.randint(0,9) loop_times=0 while loop_times<5: print loop_times try: user_input_number=int(raw_input("请输入一个整数,范围0-99:".decode('utf-8').encode('gbk'))) except Exception,e: print u"非法输入数据,必须输入整数" continue if user_input_number print u"猜小了" elif user_input_number>guess_number: print u"猜大了" else: print u"猜中了,您中奖了" loop_times +=1 if loop_times==5: #下面这行会报错,因为这里会掉用系统默认字符集(ascii)进行先解码然后再编码到gbk,ascii不能解码中文 #print "您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #下面这行可以,用utf-8来解码就可以 #print "您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行会报错,因为不能对中文的uinicode进行解码 #print u"您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行可以,有中文的unicode直接编码成gbk,可以正常显示 #print u"您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #-*-encoding:UTF-8-*- import random cishu=5 b=random.randrange(5) while cishu>0: try: #下面这句因为有u,使程序进入死循环 a=raw_input(u"输入数字:".decode("utf-8").encode("gbk"))#应该把u去掉 except Exception,e: print u"请输入数字" continue #-*-encoding:UTF-8-*- ascii = int(raw_input("input ascii code(1-127):")) print "the transformed character is:", chr(ascii) #-*-encoding:UTF-8-*- a=int(raw_input("input number a:")) b=int(raw_input("input number b:")) c=int(raw_input("input number c:")) d=int(raw_input("input number d:")) print "result of calculation of a+b-c*d:", a+b-c*d 答案: >>> a=1 #-*-encoding:UTF-8-*- minutes=7*24*60 seconds=minutes * 60 print u"一周的分钟数是:",minutes print u"一周的秒数是:", seconds 答案: >>> print "一周有%s分钟" %str(1*7*24*60) >>> print "一周有%s秒" %str(1*7*24*60*3600) '*'*100 #-*-encoding:UTF-8-*- expense = 35.27 charge= expense* 0.15 moneyForEach = (expense + charge)/3 print u"3个人平均费用是", moneyForEach,u"美元" 答案: >>> print "每人付费%s$" %str(round(35.37*1.15/3,2)) 9.计算一个12.5m X 16.7m的矩形房间的面积和周长 #-*-encoding:UTF-8-*- a = 12.5 b = 16.7 print u"长方形的长是:", a,"m" print u"长方形的宽是:", b,"m" area = a*b perimeter = 2*(a+b) print u"该长方形的面积是:", area,u"㎡"#此处注意,是中文字符 print u"该长方形的周长是:", perimeter,"m" 答案: >>> print "面积%s平方米" %str(length*width) #-*-encoding:UTF-8-*- a=float(9) b=float(2) print u"9/2的小数结果是:", a/b 答案: >>> print 9/2.0 #-*-encoding:UTF-8-*- import math print "methords to calculate 7*7*7*7:" print "math.pow(7,4):", math.pow(7,4) print "7**4:",7**4 print "7*7*7*7:",7*7*7*7 print "7**2*7**2:",7**2*7**2 #-*-encoding:UTF-8-*- ''' import sys reload(sys) sys.setdefaultencoding('UTF-8') ''' fahrenheit = float(raw_input(u"请输入华氏温度:".encode('GBK'))) centigrade = float(5)/float(9)*float(fahrenheit-32) print u"转换为摄氏温度:", round(centigrade,2) 答案: >>> print "摄氏温度:%s" %str(round(5/9.0*(a-32),1)) 9.一家商场在降价促销。如果购买金额50-100元(包含50元和100元)之间,会给10%的折扣,如果购买金额大于100元会给20%折扣。编写一程序,询问购买价格,再显示出折扣(10%或20%)和最终价格。 答案: please input your price:101 >>> if customer_price >=100: ... print "discount rate is %s" %0.2 ... print "you should pay %s" %(customer_price*0.8) ... elif customer_price>=50 and customer_price<100: ... print "discount rate is %s" %0.1 ... print "you should pay %s" %(customer_price*0.9) ... else: ... print "no discount" ... print "you should pay %s" %(customer_price) ... discount rate is 0.2 you should pay 80.8 答案: a=100 >>> if a %3==0 and a%5==0: ... print "Yes" ... else: ... print "No!" ... No! #-*-encoding:UTF-8-*- sum=0 for i in range(1,101): #print "i=:",i,"sum=:",sum sum+=i print "sum of 1+2+...100 is:",sum #-*-encoding:UTF-8-*- variate1=raw_input("input variate1:") variate2=raw_input("input variate2:") temp = variate1 variate1=variate2 variate2=temp print "exchange value of variate1 and variate2: " print "variate1=:", variate1 print "variate2=:",variate2 编写一个程序,询问用户的性别(m表示男性,f表示女性)和年龄,然后显示一条消息指出这个人是否可以加入球队,询问10次后,输出满足条件的总人数。 #-*-encoding:UTF-8-*- number=0 while number <=10: sex=0 print "number:", number while sex not in (1,2): sex=int(raw_input("please select 1 (female) or 2 ( male):")) age=int(raw_input("your age is:")) print "sex:",sex,"age:",age number+=1 if age >=10 and age<=12 and sex==1: print "you can join in the football team!" else: print "sorry, you can not join in football team!" 编写一个程序确定是不是需要在这里加油,还是可以等到接下来的第几个加油站再加油。 程序询问以下几个问题: 1)你车的油箱多大,单位升 2)目前油箱还剩多少油,按百分比算,比如一半就是0.5 3)你车每升油可以走多远(km) 提示: 油箱中包含5升的缓冲油,以防油表不准。 #-*-encoding:UTF-8-*- ''' 算法: 1、邮箱尺寸x剩余油量百分比-5L=剩余油量L 2、剩余油量x每升油走的距离=还能走的距离km 3、还能走的距离跟200km比较,如果小于等于200km就在需要在这里加油 4、还能走的距离跟200km比较,如果大于200km,小于400,可以等到下一个加油站加油 5、还能走的距离跟200km比较,如果大于200km而且能整除的话,整除结果为n,可以在接下来的第n个加油站加油 ''' fuel_capacity = float(raw_input("input your fuel box capacity (L):")) current_fuel_left_ratio =float(raw_input("input your fuel left ratio now(e.g.0.5):")) distance_per_litre=float(raw_input("how far the car can go per L (km):")) distance_can_move=(current_fuel_left_ratio*fuel_capacity-5)*distance_per_litre print "distance_can_move:",distance_can_move,"km" if distance_can_move <=200: print "you should add fuel in this petrol station, you can go %s km with the fuel left now "%distance_can_move elif distance_can_move >200 and distance_can_move <400: print "you can add fuel in next petrol station, you can go %s km with the fuel left now "%distance_can_move else: print "you can add fuel in next %s station, you can go %s km with the fuel left now"%(int(distance_can_move/200),distance_can_move) #-*-encoding:UTF-8-*- num=1 a=u"面包" b=u"热狗" c=u"番茄酱" d=u"芥末酱" e=u"洋葱" #print a,b,c,d,e list = [a,b,c,d,e] #print ",".join(list) ''' list1=[] for i in range(5): list1.append(list[i]) print ",".join(list1) ''' print "there are %s combinations"%(2**5-2**4) for i in range(2**4,2**5): list1 = [] print "combination%s:"%num num+=1 #print bin(i)[2:] combination = bin(i)[2:] print "combination:",combination for i in range(5): if combination[i]=="1": #print "combination[%s]=1"%i list1.append(list[i]) print "combination:",",".join(list1) #print "\n" 运行结果: #-*-encoding:UTF-8-*- num=1 a=u"面包" b=u"热狗" c=u"番茄酱" d=u"芥末酱" e=u"洋葱" list = [a,b,c,d,e] calory=[20,30,10,30,25] print "there are %s combinations"%(2**5-2**4) for i in range(2**4,2**5): list1 = [] list2 = [] print "combination%s:"%num num+=1 #print bin(i)[2:] combination = bin(i)[2:] print "combination:",combination for i in range(5): if combination[i]=="1": #print "combination[%s]=1"%i list1.append(list[i]) list2.append(calory[i]) print "combination:",",".join(list1) print "total calory is:",sum(list2) #-*-encoding:UTF-8-*- ''' name4="abc" name2="bcd" name5="csf" name1="daed" name3="erfd" ''' name1=raw_input("input the name1:") name2=raw_input("input the name2:") name3=raw_input("input the name3:") name4=raw_input("input the name4:") name5=raw_input("input the name5:") list = [name1,name2,name3,name4,name5] print "name list is:",",".join(list) for i in range(len(list)): for j in range(i): if list[j] > list[i]: list[j], list[i] = list[i], list[j] print "sort name list is:",",".join(list) 功能: 可以添加单词和词义,当所添加的单词已存在,让用户知道; 可以查找单词,当查找的单词不存在时,让用户知道; 可以删除单词,当删除的单词不存在时,让用户知道; 以上功能可以无限制操作,直到用户输入bye退出程序。 #-*-encoding:UTF-8-*- ''' 1.创建空字典,循环提示用户选择操作1:新增单词和词义,2:查找单词。3:删除单词4,对出 2.判断选择,如果是1:新增,提示输入单词, 判断单词是否存在字典中,如果存在,提示用户已经存在了,如果不存在,继续提示输入词义, 提示成功消息,显示单词和词义 3.如果是2查找单词,提示用户输入单词, 判断单词是否在字典中,如果没有,提示用户没有 如果有,显示该单词和词义, 4.如果是3删除单词,提示用户输入要删除的单词, 判断单词是否在字典中,如果没有提示用户没有该单词 如果有,删除该单词和词义,提示用户删除成功 5。如何是4退出,退出循环 ''' word_book={"dog":"a kind of pet"} operation = True while operation: choice = int(raw_input("\nSelect operation:\n 1: Insert word and meaning \n 2: Search word\n 3: Delete word\n 4: Exit\n ")) if choice ==1:#新增单词 add_word=raw_input("Input the word: ") if word_book.has_key(add_word):#如果要新增的单词存在 print "\nword book already have word: %s "%add_word#提示单词已经存在 else:#单词不存在 add_word_meaning=raw_input("Input the meaning of word %s: " %add_word)#提示输入单词词义 word_book[add_word]=add_word_meaning#打印该新增单词的内容 print "\nYou have added the word successfully, %s:" %add_word, word_book[add_word]#提示新增成功,显示单词和词义 print "word_book:",word_book#打印该新增单词的全部内容 if choice ==2:#查询单词 search_word=raw_input("Input the word you want to search: ")#提示输入要查询的单词 if word_book.has_key(search_word):#单词存在 print"\nThe meaning of the word %s: %s"%(search_word,word_book[search_word])#打印单词和词义 else:#单词不存在 print"\nSorry the word you search does not exist!"#提示用户该单词不存在 print "word_book:",word_book#打印该新增单词的全部内容 if choice ==3:#删除单词 del_word=raw_input("Input the word you want to delete: ")#提示输入要删除的单词 if not(word_book.has_key(del_word)):#要删除的单词不存在 print"\nSorry,the word you want to delete does not exist!" else:#单词存在 del word_book[del_word]#执行删除动作,删除该单词 print"Deleted the word %s successfully!"%del_word print "word_book:",word_book#打印该新增单词的全部内容 if choice ==4:#退出 print "bye..." exit() #-*-encoding:UTF-8-*- import random guess_number=random.randint(0,9) loop_times=0 while loop_times<5: print loop_times try: user_input_number=int(raw_input("请输入一个整数,范围0-99:".decode('utf-8').encode('gbk'))) except Exception,e: print u"非法输入数据,必须输入整数" continue if user_input_number print u"猜小了" elif user_input_number>guess_number: print u"猜大了" else: print u"猜中了,您中奖了" loop_times +=1 if loop_times==5: #下面这行会报错,因为这里会掉用系统默认字符集(ascii)进行先解码然后再编码到gbk,ascii不能解码中文 #print "您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #下面这行可以,用utf-8来解码就可以 #print "您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行会报错,因为不能对中文的uinicode进行解码 #print u"您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行可以,有中文的unicode直接编码成gbk,可以正常显示 #print u"您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number break import sys reload(sys) sys.setdefaultencoding("utf-8") ''' letters="" for i in range(26): letters=letters+chr(90-i) print letters ''' ''' letters = "" for i in range(0,26,2): letters += chr(i+65) print letters ''' ''' #translate from abcd...-->fghi.., z->e letters=raw_input("input the letters:") #print letters #print len(letters) transletter = "" for i in letters: if (ord(i)+5) < 122: print"ord(i)+5 <122" transletter+=chr(ord(i)+5) else: print"ord(i)+5>=122" transletter+=chr(ord(i)+5-26) print ("jiamihou",transletter) untransletter ="" for i in transletter: if (ord(i))<102: untransletter += chr(ord(i)-5+26) else: untransletter+= chr(ord(i)-5) print (("解码后").decode("utf-8" ), untransletter) 例题: 如果算出一个十进制数对应的二进制数: 中文算法: 自己写的: decimalism = input("input number:") binary='' while (decimalism != 0): if decimalism %2 ==0: print "decimalism %2 =0" binary += "0" print "binary:", binary decimalism /=2 print "decimalism: ", decimalism else: print "decimalism %2 =1" binary += "1" print binary decimalism /=2 print "decimalism: ", decimalism print binary[::-1] 优化之后: decimalism = input("input number:") binary="" while (decimalism != 0): binary += str(decimalism %2) decimalism /=2 print "binary:",binary[::-1] 吴老写的: number = int(raw_input("input a number:")) bin_list=[] while 1: quient=number/2 bin_list.append(str(number%2)) number=quient if number==0: break print "result:","".join(bin_list[::-1]) --------------------------------------------------------------------------------------------------------------------------------- >>> a =1 >>> isinstance(a,int) True >>> b=1L >>> isinstance(b,long) True >>> c=1+1j >>> isinstance(c,complex) True >>> d = u"a" >>> isinstance(d,unicode) True >>> e="abc" >>> isinstance(e,str) True >>> f =[1] >>> isinstance(f,list) True >>> g=(1,2) >>> isinstance(g,tuple) True >>> h ={1:2} >>> isinstance(h,dict) True >>> instance(P,type) Traceback (most recent call last): File " NameError: name 'instance' is not defined >>> isinstance(P,type) True Print 5%2 =1 Import math dir(math) Math.sqrt(4) = 2 #-*-coding:UTF-8-*- fp1 = open('d:\\testfile.txt', 'r')#手工创建文件为ANSI编码保存(gbk) info1 = fp1.read() #已知是GBK编码,解码成Unicode tmp = info1.decode('GBK') fp2 = open('d:\\testfile2.txt','w') #编码成UFT-8编码的str info2= tmp.encode('UTF-8') fp2.write(info2)#写入uft8字符,并进行保存 fp2.close() #文件会变成utf-8编码保存 test1是ANSI (GBK)编码 test2是UTF编码 #-*_ coding:UTF-8-*- s= "byte string" print type(s) #str to unicode u = s.decode() u=s.decode() print type(u) #unicode to str backToBytes=u.encode() print type(backToBytes) #获取系统编码示例: #-*-coding:UTF-8-*- import sys print sys.getdefaultencoding() #更改系统编码代码示例: #-*-coding:UTF-8-*- import sys reload(sys) sys.setdefaultencoding('UTF-8') #-*- coding: UTF-8 -*- import sys reload(sys) #去掉此行和下行,则程序出错 sys.setdefaultencoding('UTF-8') print sys.getdefaultencoding() print type(u"我") print type(u"我".encode('utf-8')) print type(u"我".decode('utf-8')) #”我”是str类型,encode前,python自动用默认编码进行decode为unicode类型,默认为ascii,则无法decode print “我”.encode(‘utf-8’).decode(‘utf-8’) #会调用默认的编码进行decode在进行encode(‘utf-8’) 注意:这里在“我”之前没有用u,所以“我”是字节型字符串,而且后边没有先decode(),不会直接编码为uft-8(需要unicode才可以),所以系统默认调用decode(utf-8)来解码为unicode,然后再编码为后边的 utf-8(encode(‘utf-8’).。。。),如果没有制定系统默认编码为uft-8,则系统默认的编码为ascii,这里系统自动调用decode(ascii)则会报错,因为ascii不会解码中文. http://www.cnblogs.com/guosq/p/6378639.html 大了提示猜小点,小了提示猜大点,5次为限,猜中了提示中奖了,然后推出 #-*-encoding:UTF-8-*- a = 98 for i in range(5): print i input_number=input("please guess the number:") if input_number >a: print("please guess smaller") elif input_number print("please guess bigger") else: print("you got it, please get your award!!") exit() if i == 4: print("you have tried 5 times,the number is:", a) #-*-encoding:UTF-8-*- ''' import sys reload(sys) print sys.getdefaultencoding() sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() ''' a = 98 for i in range(5): print i input_number=input(u"请输入一个数:".encode('gbk')) if input_number >a: print(u"请猜小一点!") elif input_number print(u"请猜大一点1") else: print(u"猜中了,您中大奖了!!") exit() if i == 4: print u"您试了5次了,没有机会了,数字是:".encode('gbk'), a #-*-encoding:UTF-8-*- import random guess_number=random.randint(0,9) loop_times=0 while loop_times<5: print loop_times try: user_input_number=int(raw_input("请输入一个整数,范围0-99:".decode('utf-8').encode('gbk'))) except Exception,e: print u"非法输入数据,必须输入整数" continue if user_input_number print u"猜小了" elif user_input_number>guess_number: print u"猜大了" else: print u"猜中了,您中奖了" loop_times +=1 if loop_times==5: #下面这行会报错,因为这里会掉用系统默认字符集(ascii)进行先解码然后再编码到gbk,ascii不能解码中文 #print "您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #下面这行可以,用utf-8来解码就可以 #print "您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行会报错,因为不能对中文的uinicode进行解码 #print u"您猜了5次了,没有机会了,正确数字是:".decode('utf-8').encode('gbk'), guess_number #下面这行可以,有中文的unicode直接编码成gbk,可以正常显示 #print u"您猜了5次了,没有机会了,正确数字是:".encode('gbk'), guess_number #-*-encoding:UTF-8-*- import random cishu=5 b=random.randrange(5) while cishu>0: try: #下面这句因为有u,使程序进入死循环 a=raw_input(u"输入数字:".decode("utf-8").encode("gbk"))#应该把u去掉 except Exception,e: print u"请输入数字" continue #-*-encoding:UTF-8-*- ascii = int(raw_input("input ascii code(1-127):")) print "the transformed character is:", chr(ascii) #-*-encoding:UTF-8-*- a=int(raw_input("input number a:")) b=int(raw_input("input number b:")) c=int(raw_input("input number c:")) d=int(raw_input("input number d:")) print "result of calculation of a+b-c*d:", a+b-c*d 答案: >>> a=1 #-*-encoding:UTF-8-*- minutes=7*24*60 seconds=minutes * 60 print u"一周的分钟数是:",minutes print u"一周的秒数是:", seconds 答案: >>> print "一周有%s分钟" %str(1*7*24*60) >>> print "一周有%s秒" %str(1*7*24*60*3600) #-*-encoding:UTF-8-*- expense = 35.27 charge= expense* 0.15 moneyForEach = (expense + charge)/3 print u"3个人平均费用是", moneyForEach,u"美元" 答案: >>> print "每人付费%s$" %str(round(35.37*1.15/3,2)) 9.计算一个12.5m X 16.7m的矩形房间的面积和周长 #-*-encoding:UTF-8-*- a = 12.5 b = 16.7 print u"长方形的长是:", a,"m" print u"长方形的宽是:", b,"m" area = a*b perimeter = 2*(a+b) print u"该长方形的面积是:", area,u"㎡"#此处注意,是中文字符 print u"该长方形的周长是:", perimeter,"m" 答案: >>> print "面积%s平方米" %str(length*width) #-*-encoding:UTF-8-*- a=float(9) b=float(2) print u"9/2的小数结果是:", a/b 答案: >>> print 9/2.0 #-*-encoding:UTF-8-*- import math print "methords to calculate 7*7*7*7:" print "math.pow(7,4):", math.pow(7,4) print "7**4:",7**4 print "7*7*7*7:",7*7*7*7 print "7**2*7**2:",7**2*7**2 #-*-encoding:UTF-8-*- ''' import sys reload(sys) sys.setdefaultencoding('UTF-8') ''' fahrenheit = float(raw_input(u"请输入华氏温度:".encode('GBK'))) centigrade = float(5)/float(9)*float(fahrenheit-32) print u"转换为摄氏温度:", round(centigrade,2) 答案: >>> print "摄氏温度:%s" %str(round(5/9.0*(a-32),1)) 9.一家商场在降价促销。如果购买金额50-100元(包含50元和100元)之间,会给10%的折扣,如果购买金额大于100元会给20%折扣。编写一程序,询问购买价格,再显示出折扣(10%或20%)和最终价格。 答案: please input your price:101 >>> if customer_price >=100: ... print "discount rate is %s" %0.2 ... print "you should pay %s" %(customer_price*0.8) ... elif customer_price>=50 and customer_price<100: ... print "discount rate is %s" %0.1 ... print "you should pay %s" %(customer_price*0.9) ... else: ... print "no discount" ... print "you should pay %s" %(customer_price) ... discount rate is 0.2 you should pay 80.8 答案: a=100 >>> if a %3==0 and a%5==0: ... print "Yes" ... else: ... print "No!" ... No! #-*-encoding:UTF-8-*- sum=0 for i in range(1,101): #print "i=:",i,"sum=:",sum sum+=i print "sum of 1+2+...100 is:",sum 高斯算法:(n+1)n/2 答案: # coding=utf-8 #-*-encoding:UTF-8-*- variate1=raw_input("input variate1:") variate2=raw_input("input variate2:") temp = variate1 variate1=variate2 variate2=temp print "exchange value of variate1 and variate2: " print "variate1=:", variate1 print "variate2=:",variate2 答案: # coding=utf-8 # coding=utf-8 编写一个程序,询问用户的性别(m表示男性,f表示女性)和年龄,然后显示一条消息指出这个人是否可以加入球队,询问10次后,输出满足条件的总人数。 #-*-encoding:UTF-8-*- number=0 while number <=10: sex=0 print "number:", number while sex not in (1,2): sex=int(raw_input("please select 1 (female) or 2 ( male):")) age=int(raw_input("your age is:")) print "sex:",sex,"age:",age number+=1 if age >=10 and age<=12 and sex==1: print "you can join in the football team!" else: print "sorry, you can not join in football team!" 答案: # coding=utf-8 编写一个程序确定是不是需要在这里加油,还是可以等到接下来的第几个加油站再加油。 程序询问以下几个问题: 1)你车的油箱多大,单位升 2)目前油箱还剩多少油,按百分比算,比如一半就是0.5 3)你车每升油可以走多远(km) 提示: 油箱中包含5升的缓冲油,以防油表不准。 #-*-encoding:UTF-8-*- ''' 算法: 1、邮箱尺寸x剩余油量百分比-5L=剩余油量L 2、剩余油量x每升油走的距离=还能走的距离km 3、还能走的距离跟200km比较,如果小于等于200km就在需要在这里加油 4、还能走的距离跟200km比较,如果大于200km,小于400,可以等到下一个加油站加油 5、还能走的距离跟200km比较,如果大于200km而且能整除的话,整除结果为n,可以在接下来的第n个加油站加油 ''' fuel_capacity = float(raw_input("input your fuel box capacity (L):")) current_fuel_left_ratio =float(raw_input("input your fuel left ratio now(e.g.0.5):")) distance_per_litre=float(raw_input("how far the car can go per L (km):")) distance_can_move=(current_fuel_left_ratio*fuel_capacity-5)*distance_per_litre print "distance_can_move:",distance_can_move,"km" if distance_can_move <=200: print "you should add fuel in this petrol station, you can go %s km with the fuel left now "%distance_can_move elif distance_can_move >200 and distance_can_move <400: print "you can add fuel in next petrol station, you can go %s km with the fuel left now "%distance_can_move else: print "you can add fuel in next %s station, you can go %s km with the fuel left now"%(int(distance_can_move/200),distance_can_move) 答案: # coding=utf-8 #-*-encoding:UTF-8-*- num=1 a=u"面包" b=u"热狗" c=u"番茄酱" d=u"芥末酱" e=u"洋葱" #print a,b,c,d,e list = [a,b,c,d,e] #print ",".join(list) ''' list1=[] for i in range(5): list1.append(list[i]) print ",".join(list1) ''' print "there are %s combinations"%(2**5-2**4) for i in range(2**4,2**5): list1 = [] print "combination%s:"%num num+=1 #print bin(i)[2:] combination = bin(i)[2:] print "combination:",combination for i in range(5): if combination[i]=="1": #print "combination[%s]=1"%i list1.append(list[i]) print "combination:",",".join(list1) #print "\n" 运行结果: 答案: # coding=utf-8 #-*-encoding:UTF-8-*- num=1 a=u"面包" b=u"热狗" c=u"番茄酱" d=u"芥末酱" e=u"洋葱" list = [a,b,c,d,e] calory=[20,30,10,30,25] print "there are %s combinations"%(2**5-2**4) for i in range(2**4,2**5): list1 = [] list2 = [] print "combination%s:"%num num+=1 #print bin(i)[2:] combination = bin(i)[2:] print "combination:",combination for i in range(5): if combination[i]=="1": #print "combination[%s]=1"%i list1.append(list[i]) list2.append(calory[i]) print "combination:",",".join(list1) print "total calory is:",sum(list2) 答案: # coding=utf-8 同学的答案: #coding=utf-8 ##定义每种食物的热量 bread_cal=800 hotdog_cal=1500 tomato_sauce_cal=800 mustcard_source_cal=1000 onion_cal=30 ##把各个食物的热量存入列表中 L=[("面包",bread_cal),("热狗",hotdog_cal),("番茄酱",tomato_sauce_cal),("芥末酱",mustcard_source_cal),("洋葱",onion_cal)] cal=0 ##循环食物的每种组合,其中面包必选,因此第一位永远是1 for i in range(0b0,0b10000): j=str('1'+bin(i)[2:].zfill(4)) ##计算每种组合的热量 for m in range(len(j)): if j[m]=='1': cal+=L[m][1] ##打印出每种组合,及对应的热量 print j,cal cal=0 #-*-encoding:UTF-8-*- ''' name4="abc" name2="bcd" name5="csf" name1="daed" name3="erfd" ''' name1=raw_input("input the name1:") name2=raw_input("input the name2:") name3=raw_input("input the name3:") name4=raw_input("input the name4:") name5=raw_input("input the name5:") list = [name1,name2,name3,name4,name5] print "name list is:",",".join(list) for i in range(len(list)): for j in range(i): if list[j] > list[i]: list[j], list[i] = list[i], list[j] print "sort name list is:",",".join(list) 答案: # coding=utf-8 功能: 可以添加单词和词义,当所添加的单词已存在,让用户知道; 可以查找单词,当查找的单词不存在时,让用户知道; 可以删除单词,当删除的单词不存在时,让用户知道; 以上功能可以无限制操作,直到用户输入bye退出程序。 #-*-encoding:UTF-8-*- ''' 1.创建空字典,循环提示用户选择操作1:新增单词和词义,2:查找单词。3:删除单词4,对出 2.判断选择,如果是1:新增,提示输入单词, 判断单词是否存在字典中,如果存在,提示用户已经存在了,如果不存在,继续提示输入词义, 提示成功消息,显示单词和词义 3.如果是2查找单词,提示用户输入单词, 判断单词是否在字典中,如果没有,提示用户没有 如果有,显示该单词和词义, 4.如果是3删除单词,提示用户输入要删除的单词, 判断单词是否在字典中,如果没有提示用户没有该单词 如果有,删除该单词和词义,提示用户删除成功 5。如何是4退出,退出循环 ''' word_book={"dog":"a kind of pet"} operation = True while operation: choice = int(raw_input("\nSelect operation:\n 1: Insert word and meaning \n 2: Search word\n 3: Delete word\n 4: Exit\n ")) if choice ==1:#新增单词 add_word=raw_input("Input the word: ") if word_book.has_key(add_word):#如果要新增的单词存在 print "\nword book already have word: %s "%add_word#提示单词已经存在 else:#单词不存在 add_word_meaning=raw_input("Input the meaning of word %s: " %add_word)#提示输入单词词义 word_book[add_word]=add_word_meaning#打印该新增单词的内容 print "\nYou have added the word successfully, %s:" %add_word, word_book[add_word]#提示新增成功,显示单词和词义 print "word_book:",word_book#打印该新增单词的全部内容 if choice ==2:#查询单词 search_word=raw_input("Input the word you want to search: ")#提示输入要查询的单词 if word_book.has_key(search_word):#单词存在 print"\nThe meaning of the word %s: %s"%(search_word,word_book[search_word])#打印单词和词义 else:#单词不存在 print"\nSorry the word you search does not exist!"#提示用户该单词不存在 print "word_book:",word_book#打印该新增单词的全部内容 if choice ==3:#删除单词 del_word=raw_input("Input the word you want to delete: ")#提示输入要删除的单词 if not(word_book.has_key(del_word)):#要删除的单词不存在 print"\nSorry,the word you want to delete does not exist!" else:#单词存在 del word_book[del_word]#执行删除动作,删除该单词 print"Deleted the word %s successfully!"%del_word print "word_book:",word_book#打印该新增单词的全部内容 if choice ==4:#退出 print "bye..." exit() 答案: # coding=utf-8 修改: # coding=utf-8 #coding=utf-8 ''' 算法: 1-输入一个数字,如果不是数字提示重新输入 2-声明一个变量存阶乘的结果,初始值=1 3-while循环,条件是输入的数字大于0 4-循环体内用阶乘结果*输入的数, 5-然后输入的数-1,每次执行循序的时候,都是阶乘的结果*上次的input number减去1,就是5*4*3*1*1,到1的时候,下次循序就不执行了 ''' #捕获异常 try: input_number = int(raw_input("input a number for factorial:")) except: print "you should input a number!" factorial_result =1 while input_number >0: print "input_number:",input_number factorial_result*=(input_number) print "factorial_result:",factorial_result input_number-=1 print "factorial_result is %s" %factorial_result 答案: # coding=utf-8 4种方法可选:活期,年利率为r1; 一年期定息,年利率为r2; 存两次半年期定期,年利率为r3 两年期定息,年利率为r4 现有本金1000元,请分别计算出一年后按4种方法所得到的本息和。 提示:本息= 本金+ 本金* 年利率* 存款期 #coding=utf-8 ''' 算法: 声明变量存本金1000元 活期的本息=本金+本金*r1*一年 一年期定息的本息=本金+本金*r2*一年 存两次半年期定息=本金+本金*r3*0.5*2 存两年期定息:本息=本金+本金*r4*0.5 ''' r1=0.03 r2=0.04 r3=0.035 r4=0.045 principal = 1000 print u"本金:%s 元" %principal print u"利率为:" print u"活期利率: %s" %r1 print u"一年期定息利率:%s" %r2 print u"存两次半年期定息利率:%s" %r3 print u"存两年期定息利率:%s" %r4 print u"一年后活期的本息为:%s 元" %(principal+principal*r1*1) print u"一年后一年期定息的本息为:%s 元" %(principal+principal*r2*1) print u"一年后存按两次半年期定息的本息为:%s 元" % (principal+principal*r3*0.5*2) print u"一年后按存两年期定息的本息为:%s 元" %(principal + principal*r4*0.5) 答案: # coding=utf-8 >>> a=input("three number seperated by ',' :") three number seperated by ',' :1,2,3 >>> a (1, 2, 3) >>> max(a) num_list=raw_input("please input three numbers,sep by ',':") 或 #coding=utf-8 num_list=raw_input("please input three numbers,sep by ',':") num_list=num_list.split(",") a=num_list[0] b=num_list[1] c=num_list[2] max=0 if a>b: max=a if max max=c print c 降序排序: #coding=utf-8 num_list=raw_input("please input three numbers,sep by ',':") num_list=num_list.split(",") a=num_list[0] b=num_list[1] c=num_list[2] max=0 if a>b: max=a if max max=c print c num_list.remove(max) if num_list[0]> num_list[1]: print max, num_list[0], num_list[1] else: print max, num_list[1], num_list[0] 能被4整数但不能被100整除,或者能被400整除的年份都是闰年。 #coding=utf-8 year = int(raw_input("input the year:")) if (year%4==0) and (year%100 != 0): print " %s is leap year" %year elif year%400 ==0: print "%s is leap year" %year else: print "%s is not leap year" %year 答案: year = int(raw_input("input a year to judge a leap year:")) 答案: # coding=utf-8 优化: # coding=utf-8 统计字符串中包含字母a的个数: s="I am a boy!" count =0 for i in s: if "a" in i: count +=1 print count 读入一个考试得分,判断这个分数是哪个等级,并输出。 等级:》=90 优 ,>=80且小于90 良,》=70 且小于80,中,》=60且<70及格 算法:1 读入一个成绩 2 使用if elif 还有else来判断成绩的等级,并输出 #-*-encoding:UTF-8-*- score = float(raw_input("输入分数:")) if score >=90: print "优" elif score >= 80: print "良" elif score >=70 and score <80: print "中" elif score >=60 and score < 70: print "及格" else: print "不及格" 字符串是小数的情况需要转换一下, 例如下面这样 int(float('2.1')) 打印10以内的偶数: >>> for i in range(0,10,2): ... print(i) ... 0 2 4 6 8 result = " " looptime =3 while looptime >=1: result = result + raw_input("输入一个单词:")+" " looptime -= 1 print result #-*-encoding:UTF-8-*- string=[] for i in range(1,51): string.append(str(i)) print string print " ".join(string) 吴老师: result = "" 吴老师: content = raw_input("please input a sentence:") result = 0 index =0 while index<=len(content)-1: if content[index] in "0123456789": result+=1 index+=1 print result 吴老师: 可以用reverse,或者切片[::-1] 第三种: list1=[1,2,3,4,5] list2=[] for i in list1: list2.insert(0,i) print list2 可以遍历的序列:列表,元祖、字符串 Python来自蟒蛇飞行马戏命名 两门语言起步,先学python,然后java Python出东西快,java很麻烦,啰唆 AI,人工智能很多都是用python做的 CPython的类型:默认是用C写的 Jpython:可以直接调用java代码 Ironpython:是.net,或者C#相关的 >>> import os >>> os.sep '\\' >>> os.linesep '\r\n' >>> os.getcwd() #获取当前路劲 'c:\\Python27\\Scripts' Eclipse+pydev Pycharm Sublime Notepad++ 写字板、 aàe bàf zàd #-*-encoding:UTF-8-*- inputnumber=raw_input("input the number:") encodenubmer="" for i in inputnumber: #print ord(i) if ord(i)+4 > 122: encodenubmer+=chr(ord(i)+4-26) elif ord(i)+4 > 90 and ord(i)+4 <97: encodenubmer+=chr(ord(i)+4-26) else: encodenubmer+=chr(ord(i)+4) print encodenubmer 吴老: letters = raw_input("please input some letter to encode:") #-*-encoding:UTF-8-*- binary="11111110" length =len(binary) result = 0 for i in range(length): result += int(binary[i])*pow(2, length-i-1) print i,int(binary[i]),pow(2,length-i-1) print result 吴老: bianary_number 11100--->第一个数字*2的0次方+第二个数字*2的一次方+第三个数字*2的2次方 循环5次: 第一次:index=0,bianary_number[index]=1,1*2**4,result=16 第二次:index=1,bianary_number[index]=1,1*2**3,result=16+8 第三次:index=2,bianary_number[index]=1,1*2**2,result=16+8+4 第四次:index=3,bianary_number[index]=0,0*2**1,result=16+8+4 第五次:index=4,bianary_number[index]=0,0*2**0,result=16+8+4 bianary_number="11100" length=len(bianary_number) #求二进制字符串的长度 result=0 #记录10进制的计算结果 index=0 #开始读取的字符串坐标 while length >0: #循环,如果长度变为0,则停止循环 result +=int(bianary_number[index])*pow(2,length-1) print index,bianary_number[index],length-1 ,result length-=1 index+=1 print result #-*-encoding:UTF-8-*- lowercase="" for i in range(97,123): lowercase += chr(i) print lowercase uppercase="" for i in range(65,91): uppercase += chr(i) print uppercase mixcase="" for i in range(65,91): mixcase+=chr(i)+chr(i+32) print mixcase 吴老: >>> letters="" >>> for s in range(65,65+26): ... letters+=chr(s)+chr(s+32) ... >>> print letters AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz >>> a=a+1,这种情况会生成一个临时变量 a+=1, 这种情况效率会高一点点 1- 先输入句子 2- 然后确定字母letters,import string,用string.letters 3- 遍历句子,判断是否是字母,然后变量加1 4- 遍历之后输出变量 #-*-encoding:UTF-8-*- import string sentence = raw_input("input yout sentence") letter_nbr=0 for i in sentence: if i in string.letters: letter_nbr+=1 print letter_nbr 吴老: >>> letters="" #-*-encoding:UTF-8-*- lowercase="" for i in range(97,123): lowercase += chr(i) print lowercase uppercase="" for i in range(65,91): uppercase += chr(i) print uppercase mixcase="" for i in range(65,91): mixcase+=chr(i)+chr(i+32) print mixcase 吴老: >>> letters="" >>> for s in range(65,65+26): ... letters+=chr(s)+chr(s+32) ... >>> print letters AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz >>> a=a+1,这种情况会生成一个临时变量 a+=1, 这种情况效率会高一点点 1- 先输入句子 2- 然后确定字母letters,import string, 用string.letters 3- 遍历句子,判断是否是字母,然后变量加1 4- 遍历之后输出变量 #-*-encoding:UTF-8-*- import string sentence = raw_input("input yout sentence") letter_nbr=0 for i in sentence: if i in string.letters: letter_nbr+=1 print letter_nbr 吴老: >>> letters="" >>> for s in range(65,65+26): ... letters+=chr(s)+chr(s+32) ... >>> print letters >>> content=raw_input("please input a sentence:") please input a sentence:I am a boy! >>> letter_count=0 >>> for s in content: ... if s in letters: ... letter_count+=1 ... >>> print letter_count #encoding=utf-8 list=range(101) print list list[57]=1 print list for i in list: if list.count(i)>1: print i 吴老: import random a=range(100) random_num = random.randint(0,99) a.insert(random_num,random_num) print random_num number = [i for i in a if a.count(i)==2] print number[0] 字典的key不能是可变元素 #encoding=utf-8 list1=range(10) list2=list1[:] def change_to_dict(a,b): dict={} for i in range(len(a)): dict[a[i]]=b[i] return dict print change_to_dict(list1,list2) 吴老: a=[1,"2",[3,4],(5,6),{7:8}] b=[0,1,2,3] d={} for i in range(len(a)): if not isinstance(a[i],(int,float,complex,long,str,unicode,tuple)): continue else: d[a[i]]=b[i] print d 或者 a=[1,"2",[3,4],(5,6),{7:8}] b=[0,1,2,3] d={} for i in range(len(a)): if not isinstance(a[i],(int,float,complex,long,str,unicode,tuple)): continue else: d[a[i]]=b[0] del b[0] print d 1.用 a=[1,2,2,3,4,5,4] b=[] for i in a: if i not in b: b.append(i) print b 2.用集合set去重 # coding=utf-8 a=[1,2,2,3,4,5,4] print list(set(a)) 3.用字典的key去重 a=[1,2,2,3,4,5,4] d={} for i in a: d[i]=None print d.keys() 4.用count # coding=utf-8 a=[1,2,2,2,2,2,2,3,4,5,4] for i in a: for j in range(a.count(i)-1): #print "i: %s j: %s"%(i,j) a.remove(i) #print "remove i:",i print a # coding=utf-8 a=[1,2,2,2,2,2,2,3,4,5,4] for i in a: print "index[i]:",a.index(i) for j in range(a.count(i)-1): a.remove(i) print a print a 这种方法不行, 因为把列表中当前下标对应的值给删了,引起下标的异常,单不确定 a=[1,2,2,2,2,2,2,3,4,5,4] for i in a: if a.count(i)>1: a.remove(i) print a 比如:a6x^6 + a5x^5 + a4x^4 + a3x^3 + a2x^2 + a1x^1 + a0 # coding=utf-8 a =[] for i in range(6,-1,-1): if i == 0: a.append("a%s"%i) else: a.append("a%s*^%s"%(i,i)) print "+".join(a) 笨方法: # coding=utf-8 print list(range(1,7))[::-1] for i in list(range(1,7))[::-1]: print "a"+str(i)+"*^"+str(i)+'+', print "a0" 吴老: 吴老: # coding=utf-8 result=[] for i in range(6,-1,-1): if i == 0: result.append("a0") break result.append("a%sx^%s" %(i,i)) print "+".join(result) # coding=utf-8 a =['alark','philipu','carry','dererk'] d={} for i in a: d[i]="".join(a).count(i[0]) print d 或者: name_list=['foster',"janet",'jessus','david'] count_dict={} for i in name_list: count=0 for j in name_list: if j.count(i[0])>=1: count+=j.count(i[0]) count_dict[i]=count print count_dict 能构成三角形三边关系:三边都大于零两边之和大于第三边,两边之差小于第三边 # coding=utf-8 a=int(raw_input("input number a:")) b=int(raw_input("input number b:")) c=int(raw_input("input number c:")) if (a+b > c) and (a-b print u"是三角形" else: print u"不是三角形" 最优解: import math 例如: seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq, 10) print "New Dictionary : %s" % str(dict) 结果: New Dictionary : {'age': 10, 'name': 10, 'sex': 10} # coding=utf-8 seq=('name','age','sex') dict = {} for i in seq: dict[i]=10 print dict {}.fromkeys(['a',’b’]) 这样可以 >>> {}.fromkeys(['a',’b’]) {'a': None, 'b': None} 但是一个list,是不能整体作为字典的key的,因为他可变 #encoding=utf-8 import traceback#追踪报错信息 def f_keys(keys,value=None): dict_b={} if isinstance(keys,(list,tuple,str,set)): for i in keys: try: hash(i) except: print "value %s can not be key of dict,because of: %s" %(i,traceback.format_exc()) if i not in dict_b: dict_b[i] = value return dict_b else: print "data: %s is not iterable" %repr(keys) print f_keys([1,2,3]) c:\Python27\Scripts>python task_test.py {1: None, 2: None, 3: None} 如果把列表参数中把某个元素替换成一个列表,就会报错,不可哈希 print f_keys([1,[2,1],2,3]) c:\Python27\Scripts>python task_test.py value [2, 1] can not be key of dict,because of: Traceback (most recent call last): File "task_test.py", line 8, in f_keys hash(i) TypeError: unhashable type: 'list' Traceback (most recent call last): File "task_test.py", line 18, in print f_keys([1,[2,1],2,3]) File "task_test.py", line 12, in f_keys if i not in dict_b: TypeError: unhashable type: 'list' 这种方法是组合成一个字典,单没有异常处理 >>> exec('a="".join(["{",":1,".join(["a","b"]),":1}"])') >>> >>> print a {a:1,b:1} 1、异常处理,我们要保证系统或者方法的健壮性 2、提示信息要准确 Eval >>> a=raw_input("pls select your choice:") pls select your choice:x >>> d={"x":"result"} >>> d[a] 'result' >>> def result(x): ... return x**2 ... >>> eval(d[a]+"(2)") 4 >>> [i for i in dir(a) if i.startswith("spli")] [] >>> [i for i in dir(a) if i.startswith("rever")] ['reverse'] 1切片 >>> a [4, 3, 2, 1] >>> a[::-1] [1, 2, 3, 4] 2Reverse >>> a.reverse >>> a [4, 3, 2, 1] 3推导列表 >>> [a[-i-1] for i in range(len(a))] ['g', 'f', 'e', 'd', 'c', 'b', 'a'] >>> "".join([a[-i-1] for i in range(len(a))]) 'gfedcba' 装饰器,需要研究一下 #encoding=utf-8 a="abcdefg" def outer(result): def inner(a): x=result(a) return [a[i] for i in x] return inner @outer def result(a): return [-1-1 for i in range(len(a))] print result(a) while循环 >>> n=len(a) >>> n 7 >>> while n>0: ... n-=1 ... print a[n] ... e d c b a 还有 >>> a 'abcdefg' >>> map(lambda n:a[-n-1],range(len(a))) ['g', 'f', 'e', 'd', 'c', 'b', 'a'] >>> 还有 >>> [a[i] for i in reversed(range(len(a)))] ['g', 'f', 'e', 'd', 'c', 'b', 'a'] >>> list(reversed(range(len(a)))) [6, 5, 4, 3, 2, 1, 0] # coding=utf-8 input_str=raw_input("input string:") print input_str[::-1] # coding=utf-8 input_str=raw_input("input string:") list=[] for i in input_str[::-1]: list.append(i) print "".join(list) # coding=utf-8 number=input("input a int number:") result=1 for i in range(1,number+1): result *= i print result 另一种: >>> "".join(["%s*" % i for i in range(1,d+1)])[:-1] '1*2*3*4*5*6*7*8*9*10' >>> d 10 >>> eval("".join(["%s*" % i for i in range(1,d+1)])[:-1]) 3628800 另一种: >>> "*".join([str(i) for i in range(1,d+1)]) '1*2*3*4*5*6*7*8*9*10' >>> eval("*".join([str(i) for i in range(1,d+1)])) 3628800 # coding=utf-8 list=[] for i in range(1,11): list.append("1/%s" %i) print ",".join(list) 另一种: s=”” >>> for i in range(1,d+1): ... s+="1/%s," %i ... >>> s '1/1,,1/2,,1/3,,1/4,,1/5,,1/6,,1/7,,1/8,,1/9,,1/10,,1/1,1/2,1/3,1/4,1/5,1/6,1/7,1/8,1/9,1/10,' >>> s[:-1] '1/1,,1/2, Str有join方法,center,count Li 可哈希的就是唯一的, >>> a="asdfsdf" >>> a.split() ['asdfsdf'] >>> "i am a boy".split() ['i', 'am', 'a', 'boy'] >>> a=[] -1585925417 >>> hash("asd") -1585925417 >>>a.extend("asd") >>> a ['a', 's', 'd'] >>> a ['a', 's', 'd', 1, 2] >>> 装饰器方法: #coding=utf-8 def fun(n): if n==2: return str(1)+"/"+str(n) else: return fun(n-1)+(","+str(1)+"/"+str(n)) if __name__=="__main__": print fun(10) 装饰器方法: #coding=utf-8 def deco(fun): def _deco(n): global result result+=fun(n) return _deco @deco def fun(n): return str(1)+"/"+str(n)+"," if __name__=="__main__": result="" for i in range(2,11): fun(i) print result[:-1] 浅拷贝,一层元素会变,二层元素不会变 深拷贝,一层元素会变,二层元素也会变 张文琪: 浅拷贝,对象会变,元素不会变 >>> a=[1,2,3,[4,5]] >>> a [1, 2, 3, [4, 5]] >>> b=copy.copy(a) >>> a [1, 2, 3, [4, 5]] >>> b [1, 2, 3, [4, 5]] >>> id(a) 87626176 >>> id(b) 87676328 >>> a is b False 无论深浅拷贝,拷贝后的两个列表不是一个对象,但是容器里面的元素是一样的 浅拷贝后,列表a变了,b也跟着便 深拷贝,列表中的可变对象是有区别的,操作一个,另一个不会受影响 >>> c=copy.deepcopy(a) >>> a [1, 2, 3, [4, 5, 5]] >>> c [1, 2, 3, [4, 5, 5]] >>> id(a),id(b) (87626176, 87676328) >>> id(a[3]),id(c[3]) (87611032, 87676368) >>> id(a),id(c) (87626176, 87590512) >>> a[3].append(6) >>> a [1, 2, 3, [4, 5, 5, 6]] >>> c [1, 2, 3, [4, 5, 5]] >>> b [1, 2, 3, [4, 5, 5, 6]] # coding=utf-8 x,y = input("input two int number x,y:") def getpow(x,y): result =x**y print "result of getpow:",result getpow(x,y) # coding=utf-8 string = raw_input("input a letter:") number = int(raw_input("input a number:")) list=[] for i in range(1,number+1): list.append(string*i) print "+".join(list) 装饰器,就是这么个故事,函数a说,我是装饰器啊,其他哪个函数顶着我,我就吃了谁,然后吐出来我的和你的返回结果 如果你有做过testng的UI自动化,@beforetest,@beformethod,这种都是testng框架的装饰器。包括,我们学的@classmethod,@staticmethod 闭包就是一个函数把外部的那些不属于自己的对象也包含(闭合)进来了。 >>> def x(f): ... print 1 ... >>> @x#等价于x(y) ... def y(): ... print 2 ... 1 >>> x(y) 1 >>> type(x(y)) 1 >>> x(y)() 1 Traceback (most recent call last): File " TypeError: 'NoneType' object is not callable >>> 不执行的话: # coding=utf-8 import random list=[] for i in range(100): list.append(random.randint(0,9)) print list print sum(list) # coding=utf-8 even_sum=0 odd_sum=0 print range(1,101) for i in range(1,101): if i%2 ==0: even_sum +=i else: odd_sum +=i print "even sum of 1-100:%s"%even_sum print "odd sum of 1-100:%s"%odd_sum n3=re.findall(r"(\d*[13579]{1})\,",(str(range(1,101))[:-1]+",")) # coding=utf-8 list=[] for i in range(10): list.append(int(raw_input("input a number total 10 times:"))) print "the ten numbers are: %s"%list print "Max of the numbers is:%s"%max(list) print "Min of the numbers is:%s"%min(list) print sorted(n)[0],sorted(n)[-1] # coding=utf-8 num=input("input a number no more than 5 digits:") print "the digits of num is:%s"%(len(str(num))) print "descend order of num is:%s"%(str(num)[::-1]) y=re.search("[1-9]+\d*","%s" % x).group( print [y[-i] for i in range(1,len(y)+1)] # coding=utf-8 for i in range(100,1000): if int(str(i)[0])**3+int(str(i)[1])**3+int(str(i)[2])**3 == i: print i # coding=utf-8 list=[] n=input("input the number:") for i in range(1,n+1): list.append("%s!"%i) print "+".join(list) #coding=utf-8 import random result={} num=0 for i in range(1,20): result["5 cent"]=i for j in range(1,(100-i*5)/2): result["2 cent"]=j num+=1 result["1 cent"]=100-i*5-2*j print result,"5cent+2cent:%s" %(i*5+j*2) print "there r %s ways to make up 1 yuan"%num #coding=utf-8 sentence="i am student of glory road" word=raw_input("input a word to find:") print sentence.split() for i in sentence.split(): if i==word: print "index of the word '%s' is %s" %(word,sentence.split().index(i)) #coding=utf-8 decimal_num=int(raw_input("input a decimal number:")) binary=[] flag=True while flag: binary.append(str(decimal_num%2)) if decimal_num/2 ==0: flag=False decimal_num /=2 print "".join(binary[::-1]) #-*-coding:utf-8- list=[] num=raw_input("input a number:") for i in num: list.append(str(int(i)+1)) print "".join(list) 算法: int("".join(map(lambda x:str(int(x)+1),"123"))) 算法: 生成一个4位的随机大写字母 成成一个3位随机的小写字母 生成一个3位随机的数字 把三种取值组合然后打乱 输出 #-*-coding:utf-8- import random import string def passwd(): list1=random.sample(string.uppercase,4) list2=random.sample(string.lowercase,3) list3=random.sample(string.digits,3) pw=list1+list2+list3 random.shuffle(pw) return "".join(pw) print passwd() 吴老: 1 想办法生成4个随机大写字母的字符串 #coding=utf-8 import random import string def get_random_password(): a=list(string.uppercase) random.shuffle(a) print a[:4] str1=a a=list(string.lowercase) random.shuffle(a) print a[:3] str2=a a=list(string.digits) random.shuffle(a) print a[:3] str3=a result =str1+str2+str3 return "".join(result) if __name__ == "__main__": print get_random_password() 优化: #coding=utf-8 import random import string def get_random_elements(s,length): a=list(s) random.shuffle(a) print a[:length] return a[:length] def get_random_password(): return "".join(get_random_elements(string.uppercase,4)+get_random_elements(string.lowercase,3)+get_random_elements (string.digits,3)) if __name__ == "__main__": print get_random_password() #coding=utf-8 for i in range(10): #print "i:",i for j in range(0,10-i): #print "j:",j print "", for k in range(10-i,10): #print "k:",k print "*", print "" #coding=utf-8 for i in range(10): #print "i:",i for j in range(0,i): #print "j:",j print "", for k in range(i,10): #print "k:",k print "*", print "" Degug: #coding=utf-8 for i in range(11): print "i:",i for j in range(0,11-i): print "j:",j, print "*", for k in range(11-i,11): print "k:",k, print "$", print "" #coding=utf-8 for i in range(11): #print "i:",i for j in range(0,11-i): #print "j:",j, print "", for k in range(11-i,11): #print "k:",k, if i<10: if ((k==11-i) or (k ==10)): print "$", else: print " ", else: print "$", print "" #coding=utf-8 list=[] for i in range(2000,3001): if (i%7 ==0)and (i%5!=0): list.append(str(i)) print ",".join(list) #coding=utf-8 for i in range(1,10): for j in range(i,10): print "%s * %s =%s" %(i,j,i*j) #coding=utf-8 i=1.0 n=1.0 list=["1"] while 1/i >1.0/10: if i%2==0: list.append("+ 1/(%s+1)"%i) else: list.append("- 1/(%s+1)"%i) i+=1 list.append("...") print "".join(list) i=1.0 print "i:%s,n:%s" %(i,n) while 1/i >=1/(10e5+1): if i%2==0: n+=1/(i+1) else: n+=-1/(i+1) i+=1 print n #coding=utf-8 input_letter="abcdwxyzABCDWXYZ" print input_letter list=[] for i in input_letter: if i>='a' and i<'w': list.append(chr(ord(i)+4)) if i >='w' and i<='z': list.append(chr(ord(i)-26+4)) if i>='A' and i<'W': list.append(chr(ord(i)+4)) if i >='W' and i<='Z': list.append(chr(ord(i)-26+4)) print "".join(list) 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 #coding=utf-8 for i in range(1,5): a=i for j in range(5): print i, i+=a print "" list1=[4,3,6,7,4,2] list2=[] for i in range(len(list1)): if i ==0: list2.append(list1[0]) else: list2.append(list1[i]+list1[i-1]) print list1 print list2 ip_list=['192.168.1.1','192.168.1.2','192.168.1.2','192.168.1.4','192.168.1.4','192.168.1.2','192.168.1.4',] count_dict={} for i in ip_list: count_dict[i] =ip_list.count(i) for k,v in count_dict.items(): if v == max(count_dict.values()): print k 8、打印100以内的素数 #coding=utf-8 list=["2"] for i in range(3,101): for j in range(2,i): if i%j ==0: break else: list.append(str(i)) print " ".join(list) #coding=utf-8 str=raw_input("input your calculation:") print "str:",str print "result:",eval(str) #coding=utf-8 list=[0,1] seq=[] for i in range(21): list.append(list[-1]+list[-2]) print list[2:] for i in range(len(list[2:])-1): seq.append("%s/%s"%(list[2:][i+1],list[2:][i])) print seq print "calculation of:","+".join(seq),"is :" print eval("+".join(seq)) #coding=utf-8 for i in range(0,10): for k in range(10-i): print " ", for j in range(2*i-1): print "$", print "" #coding=utf-8 for i in range(0,10): for k in range(10-i): print " ", for j in range(2*i-1): if j ==0 or j==(2*i-1-1) or i == 9: print "$", else: print " ", print "" #coding=utf-8 for i in range(10,0,-1): for k in range(10-i): print " ", for j in range(2*i-1): if j ==0 or j==(2*i-1-1) or i == 10: print "$", else: print " ", print "" #coding=utf-8 for i in range(10): for i in range(10-i): print "*", print "" #coding=utf-8 for i in range(10): for k in range(10-i): if i==0 or k==0 or k==(10-i-1): print "*", else: print " ", print "" print " "*2,"*"*7 print " ","** *" print " ","**" print "**" print "**" print " ","**" print " ","** *" print " "*2,"*"*7 num=0 for i in range(11): for j in range(11): if j == 0 or j == 10 or j == num: print "*", else: print " ", print "" num+=1 #print "num:",num for i in range(11): for j in range(11): if i == 0 or i == 10 or j==0 or j==10: print "*", else: print " ", print "" for i in range(11): for j in range(11): if j==0 or j==10 or i ==5: print "*", else: print " ", print "" #encoding=utf-8 ''' 分析 b=[1] b = [1] + [b[i] + b[i+1] for i in range(len(b)-1)] + [1] b=[1],range(len(b)-1)是空的, b=[1,1] len(b)-1=1 range(len(b)-1)=[0] i = 0: b=[1] + [b[0] + b[1]] + [1] b=[1]+[2]+[1] b=[1,2,1] b=[1,2,1] len(b)-1=2 range(len(b)-1)=range(2)=[0,1] [b[i] + b[i+1] for i in range(len(b)-1)] =[b[i] + b[i+1] for i in range(2)] =[b[0]+b[1],b[1]+b[2]]=[3,3] b=[1]+[3,3]+[1]=[1.3.3.1] b=[1.3.3.1] [b[i] + b[i+1] for i in range(len(b)-1)] =[b[i] + b[i+1] for i in range(3)] =[b[0]+b[1],b[1]+b[2],+[b[2]+b[3]]] =[4,6,4] b=[1]+[4,6,4]+[1] b=[1,4,6,4,1] b=[1,5,10,10,5,1] b=[1,6,15,20,15,6,1] b=[1,7,21,35,35,21,7,1] b=[1,8,28,56,70,56,28,8,1] ''' num=input(u"输入行数:".encode('gbk')) def get_max_len(x): b=[1] for n in range(x): b=[1]+[b[i]+b[i+1] for i in range(len(b)-1)]+[1] s=" ".join(map(str,b)) if n==(x-1): return len(s) print "get_max_len:",get_max_len(num) def yanghui(m): b=[1] max_len=get_max_len(m) #print "max len:",max_len print '1'.center(max_len, " ") #print "m:",m for n in range(m): #print "n:",n b=[1]+[b[i]+b[i+1] for i in range(len(b)-1)]+[1] s=" ".join(map(str,b)) #print "s:",s print s.center(max_len," ") return " " print "yanghui(%s):\n" %num print yanghui(num) 17、打印如图所示图案,要求支持指定行数,但行数必须是奇数行 #encoding=utf-8 #1 1 3 3 5 5 7 7 def print_icon(m): if m%2==1: for i in range(1,m+1,2): #print i print "* "*i for j in range(m-2,0,-2): #print j print "* "*j else: print "the number is not odd" return "" n=input("input the odd number:") print print_icon(n) - 18、要求实现一函数,该函数用于求两个集合的差集,结果集合中包含所有属于第一个集合但不属于第二个集合的元素 >>> b set([1, 2, 3]) >>> a set([1, 2, 3, 4, 5]) >>> a-b set([4, 5]) >>> a-(a-b) set([1, 2, 3]) >>> #encoding=utf-8 s="i love you not because of who you are, but because of who i am with you " a=s.split() d={} for i in a: d[i]=len(i) max_len= max(d.values()) list=[] for i in range(len(a)): if len(a[i])==max_len: list.append((a[i],i)) print list #encoding=utf-8 a=[1,2,3,4,5,6,76,5,3,2,3,6,5,44] print a print "max of a:",max(a) #encoding=utf-8 a=[1,2,3,4,5,6,76,5,3,2,3,6,5,44] b=sorted(a,reverse=True) print a print b print "max of a:", b[0] 按引用复制: a=[1,2,3,['a','b']] print "a:",a b=a print "b:",b print "a.append(4):" a.append(4) print "a:",a print "b:",b 按值拷贝 #encoding=utf-8 a=[1,2,3,['a','b']] print "a:",a b=a[:] print "b:",b print "a.append(4):" a.append(4) print "a:",a print "b:",b #encoding=utf-8 list1=[1,2,3,4,5,6] list2=[5,6,7,8,9,0] same_element=[] different_element=[] for i in list1: if i in list2: same_element.append(i) else: different_element.append(i) for j in list2: if j not in list1: different_element.append(j) print "same element of two lists are:",same_element print "different element of two lists are:",different_element 练习题4:数字和字母混合的list中,奇数位元素加1,偶数位加2 练习题5:递归处理嵌套的list 练习题6: 遍历list,但是list中元素的数据类型不定,有可能有嵌套的list,嵌套的tuple,dict等。(没有多重嵌套) 练习题7: 通过遍历list去掉重复部分 练习题8:1个纯数字的list中,分别输出奇数坐标数字或偶数坐标数字 练习题9:找到序列中最大的元素,自己写算法实现,不能用现有函数 练习题10:返回列表中第二大元素 练习题11:键盘读入一字符串,逆序输出 #encoding:utf-8 list1=[] list2=[] for i in range(0,100,2): list1.append(i) print list1 for i in range(1,100,2): list2.append(i) print list2 算法: #encoding:utf-8 odd_list=[] even_list=[] for i in range(0,101): if i%2 ==0: even_list.append(i) else: odd_list.append(i) print "odd list:",odd_list print "even list:",even_list 检验给出的路径是否是一个文件: 检验给出的路径是否是一个目录: 判断是否是绝对路径: 检验给出的路径是否真地存: #coding=utf-8 import re s="i love you not because of who you are, but because of who i am when i am with you" content=re.findall(r"\b\w",s) print content c:\Python27\Scripts>python task_test.py ['i', 'l', 'y', 'n', 'b', 'o', 'w', 'y', 'a', 'b', 'b', 'o', 'w', 'i', 'a', 'w', 'i', 'a', 'w', 'y'] import re s="i love you not because 12sd 34er 56df e4 54434" content=re.findall(r"\b\d",s) print content c:\Python27\Scripts>python task_test.py ['1', '3', '5', '5'] >>> print re.match(r"\w+","123sdf").group() 123sdf #coding=utf-8 import re s="i love you not because\n12sd 34er 56\ndf e4 54434" content=re.findall(r"\w+",s,re.M) print content c:\Python27\Scripts>python task_test.py ['i', 'love', 'you', 'not', 'because', '12sd', '34er', '56', 'df', 'e4', '54434'] import re s="'bat', 'bit', 'but', 'hat', 'hit', 'hut" content=re.findall(r"..t",s) print content c:\Python27\Scripts>python task_test.py ['bat', 'bit', 'but', 'hat', 'hit', 'hut'] #coding=utf-8 import re s="awoeur awier !@# @#4_-asdf3$^&()+?> content=re.findall(r".*",s,re.DOTALL) print s print content c:\Python27\Scripts>python task_test.py awoeur awier !@# @#4_-asdf3$^&()+?> $ ['awoeur awier !@# @#4_-asdf3$^&()+?> #coding=utf-8 import re s="""se234 1987-02-09 07:30:00 1987-02-10 07:25:00""" content=re.findall(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}",s,re.M) print s print content c:\Python27\Scripts>python task_test.py se234 1987-02-09 07:30:00 1987-02-10 07:25:00 ['1987-02-09 07:30:00', '1987-02-10 07:25:00'] #coding=utf-8 import re s="""[email protected], [email protected], [email protected] [email protected], [email protected] content=re.sub(r"\w+@\w+.com","[email protected]",s) print s print "_______________________________________" print content c:\Python27\Scripts>python task_test.py [email protected], [email protected], [email protected] [email protected], [email protected] _______________________________________ [email protected], [email protected], [email protected] [email protected], [email protected] >>> re.findall(r"\\home","skjdfoijower \home \homewer") ['\\home', '\\home'] #coding=utf-8 import re s="""i love you not because of who 234 you are, 234 but 3234ser because of who i am when i am with you""" content=re.findall(r"\b[a-zA-Z]+\b",s) print content c:\Python27\Scripts>python task_test.py ['i', 'love', 'you', 'not', 'because', 'of', 'who', 'you', 'are', 'but', 'because', 'of', 'who', 'i', 'am', 'when', 'i', 'am', 'with', 'you'] import re s="""[email protected], [email protected] [email protected] [email protected] [email protected] saldkfj.com [email protected]""" content=re.findall(r"\w+@\w+.com",s) print content c:\Python27\Scripts>python task_test.py ['[email protected]', '[email protected]', '[email protected]', '[email protected]'] 域名由各国文字的特定字符集、英文字母、数字及“-”(即连字符或减号)任意组合而成, 但开头及结尾均不能含有“-”,“-”不能连续出现。域名中字母不分大小写。域名最长可达60个字节(包括后缀.com、.net、.org等)。 比如:s = '光荣之路官网' 要求,给出的正则表达式能兼顾所有链接地址。 7、匹配ip的正则表达式: r'^(([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$' >>> re.match(r'^(([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$',"10.192.178.11").group() '10.192.178.11' #encoding=utf-8 import time time1= time.time() n=2 for i in range(100000): n=n*2 #print n time2=time.time() total_time=time2-time1 print "total time of program:%.2f sec"%total_time c:\Python27\Scripts>python task_test.py total time of program:2.94 sec >>> import time >>> time.localtime() time.struct_time(tm_year=2018, tm_mon=2, tm_mday=24, tm_hour=19, tm_min=45, tm_sec=24, tm_wday=5, tm_yday=55, tm_isdst=0) >>> time.mktime(time.localtime()) 1519472732.0 >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) '2018-02-24 19:46:50' >>> str_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) >>> str_time '2018-02-24 19:49:54' >>> time_array=time.strptime(str_time,"%Y-%m-%d %H:%M:%S") >>> time_array time.struct_time(tm_year=2018, tm_mon=2, tm_mday=24, tm_hour=19, tm_min=49, tm_sec=54, tm_wday=5, tm_yday=55, tm_isdst=-1) >>> custome_time=time.strftime("%Y-%m-%d",time_array) >>> custome_time '2018-02-24' >>> time_stamp=time.time() >>> time_array=time.localtime(time_stamp) >>> time_array time.struct_time(tm_year=2018, tm_mon=2, tm_mday=24, tm_hour=19, tm_min=58, tm_sec=8, tm_wday=5, tm_yday=55, tm_isdst=0) >>> format_time=time.strftime("%Y-%m-%d %H",time_array) >>> format_time '2018-02-24 19' #encoding=utf-8 import time import os os.chdir("d:\\") print os.getcwd() dir_name=time.strftime("%Y-%m-%d",time.localtime()) print dir_name os.mkdir(dir_name) print os.listdir(os.curdir) os.chdir(os.getcwd()+dir_name) print os.getcwd() try: fp=open("%s.txt"%dir_name,"w") except: print "can not" fp.write(u"你好".encode("gbk")) fp.close() with open("%s.txt"%dir_name) as fp: print fp.readline() c:\Python27\Scripts>python task_test.py d:\ 2018-02-25 ['$RECYCLE.BIN', '.one', '1111111111111.txt', '2018-02-25', '2018-02-252018-02-25.txt', '360Downloads', '360\xb0\xb2\xc8\xab\xe4\xaf\xc0\xc0\xc6\xf7\xcf\xc2\xd4\xd8', '360\xc7\xfd\xb6\xaf\xb4\xf3\xca\xa6\xc4\xbf\xc2\xbc', 'a.jpg', 'a.py', 'a.pyc', 'a.txt', 'b.jpg', 'CitrixReceiverWeb.exe', 'codexx.py', 'codexx.pyc', 'dir', 'error.txt', 'KingsoftData', 'QMDownload', 'QQPCMgr', 'sdffffffffffff.txt', 'sys.txt', 'System Volume Information', 'test', 'test2', 'testfile.txt', 'testfile2.txt', 'time', 'xx.txt', 'xxx.txt', '~$\xd3\xa2\xd3\xef\xb1\xca\xbc\xc7.docx', '\xb2\xe2\xca\xd4\xd7\xca\xc1\xcf', '\xd3\xa2\xd3\xef\xb1\xca\xbc\xc7.docx'] d:\2018-02-25 你好 三天前: >>> from datetime import * >>> today=date.today() >>> today datetime.date(2018, 2, 25) >>> print today-timedelta(days=3) 2018-02-22 三小时前 >>> threeHoursAgo=datetime.datetime.now()-datetime.timedelta(hours=3) >>> print str(threeHoursAgo) 2018-02-25 17:31:41.932000 >>> print str(threeHoursAgo)[:-7] 2018-02-25 17:31:41 三分钟前: >>> datetime.datetime.now() datetime.datetime(2018, 2, 25, 20, 34, 17, 298000) >>> str(datetime.datetime.now()) '2018-02-25 20:34:25.855000' >>> str(datetime.datetime.now())[:-7] '2018-02-25 20:34:44' >>> threeMinutesAgo=datetime.datetime.now()-datetime.timedelta(minutes=3) >>> print str(threeHoursAgo)[:-7] 2018-02-25 17:31:41 >>> date.today() datetime.date(2018, 2, 25) >>> date.today()-timedelta(days=1) datetime.date(2018, 2, 24) >>> date.today()+timedelta(days=1) datetime.date(2018, 2, 26) Import datetime >>> date.today() datetime.date(2018, 2, 25) >>> str(datetime.datetime.now()) '2018-02-25 20:34:25.855000' >>> str(datetime.datetime.now()) '2018-02-25 20:38:39.643000'1、用ascii码进行字符串的输出
2、算出一个十进制数对应的二进制数:
3、对文件的内容进行编码转换
4、猜数字
5、输入1-127的ascii码并输出对应字符
6、输入a,b,c,d4个整数,计算a+b-c*d的结果
>>> b=2
>>> c=3
>>> d=4
>>> print eval("a+b-c*d")
-9
>>> print a+b-c*d
-97、计算一周有多少分钟、多少秒钟
一周有10080分钟
一周有36288000秒8、3个人在餐厅吃饭,想分摊饭费。总共花费35.27美元,他们还想给15%的小费。每个人该怎么付钱,编程实现
每人付费13.56$
面积208.75平方米8.怎么得到9 / 2的小数结果
4.59.python计算中7 * 7 *7 * 7,可以有多少种写法
10.写程序将温度从华氏温度转换为摄氏温度。转换公式为C = 5 / 9*(F - 32)
摄氏温度:-1.110、判断一个数n能否同时被3和5整除
11、求1 + 2 + 3 +….+100
12、交换两个变量的值
13、一个足球队在寻找年龄在10到12岁的小女孩(包括10岁和12岁)加入。
14、长途旅行中,刚到一个加油站,距下一个加油站还有200km,而且以后每个加油站之间距离都是200km。
15、现有面包、热狗、番茄酱、芥末酱以及洋葱,数字显示有多少种订购组合,其中面包必订,0不订,1订,比如10000,表示只订购面包
16、基于上题:给出每种食物的卡路里(自定义),再计算出每种组合总共的卡路里
17、输入5个名字,排序后输出
18、实现一个简单的单词本
0、猜数字
1、用ascii码进行字符串的输出
2、算出一个十进制数对应的二进制数:
3、对文件的内容进行编码转换
4、猜数字
5、输入1-127的ascii码并输出对应字符
6、输入a,b,c,d4个整数,计算a+b-c*d的结果
>>> b=2
>>> c=3
>>> d=4
>>> print eval("a+b-c*d")
-9
>>> print a+b-c*d
-97、计算一周有多少分钟、多少秒钟
一周有10080分钟
一周有36288000秒'*'*100
8、3个人在餐厅吃饭,想分摊饭费。总共花费35.27美元,他们还想给15%的小费。每个人该怎么付钱,编程实现
每人付费13.56$
面积208.75平方米8.怎么得到9 / 2的小数结果
4.59.python计算中7 * 7 *7 * 7,可以有多少种写法
10.写程序将温度从华氏温度转换为摄氏温度。转换公式为C = 5 / 9*(F - 32)
摄氏温度:-1.110、判断一个数n能否同时被3和5整除
11、求1 + 2 + 3 +….+100
count =0
for i in range(1,101):
count+=i
print count 12、交换两个变量的值
a=1
b=2
a,b = b,a
print a,b
a=1
b=2
tmp = a
a=b
b=tmp
print a,b13、一个足球队在寻找年龄在10到12岁的小女孩(包括10岁和12岁)加入。
count =0
for i in range(10):
student_info = raw_input("please input sex and age,sep by ',':")
sex = student_info.split(',')[0]
age = student_info.split(',')[1]
if sex.lower() == "f" and float(age) >=10 and float(age)<=12:
count+=1
print u"满足条件的孩子有 %s 个" %count 14、长途旅行中,刚到一个加油站,距下一个加油站还有200km,而且以后每个加油站之间距离都是200km。
car_gas_volume = 200
car_current_gas_volume = 150
car_100_km_gas_consume = 10
gas_station_gap_distance=200
print u"请在第 %s 个加油站加油" %int((car_current_gas_volume-5)/car_100_km_gas_consume*100/gas_station_gap_distance) 15、现有面包、热狗、番茄酱、芥末酱以及洋葱,数字显示有多少种订购组合,其中面包必订,0不订,1订,比如10000,表示只订购面包
bread=["b1"]
hotdog=["h1","h0"]
tomato_jam=["t1","t0"]
jiemo=["j1","j0"]
onion=["o1","o0"]
result =[]
for b in bread:
for h in hotdog:
for t in tomato_jam:
for j in jiemo:
for o in onion:
result.append(b+" "+h+" "+t+" "+j+" "+o)
print len(result)
print result
for i in result:
print i 16、基于上题:给出每种食物的卡路里(自定义),再计算出每种组合总共的卡路里
bread=["b1"]
hotdog=["h1","h0"]
tomato_jam=["t1","t0"]
jiemo=["j1","j0"]
onion=["o1","o0"]
result =[]
bread_calori=1
hotdog_calori=2
tomato_jam_calori=3
jiemo_calori=4
onion_calori=5
for b in bread:
for h in hotdog:
for t in tomato_jam:
for j in jiemo:
for o in onion:
result.append(b+" "+h+" "+t+" "+j+" "+o)
print len(result)
print result
for i in result:
calori_count=0
for x in i.split():
if x == "b1":
calori_count+=bread_calori
if x =="h1":
calori_count+=hotdog_calori
if x == "j1":
calori_count+=jiemo_calori
if x =="o1":
calori_count+=onion_calori
if x =="t1":
calori_count+=tomato_jam_calori
print i,u"组合的卡路里总和是:",calori_count,u"千卡" 17、输入5个名字,排序后输出
name_list=[]
for i in range(5):
name_list.append(raw_input("input a name:").strip())
name_list.sort()
print name_list 18、实现一个简单的单词本
word_dict = {}
help = u'''
1:add a word
2:find a word meaning
3: delete a word
input bye to exit
'''
print help
while 1:
command = raw_input("please input your command:")
if command ==str(1):
word = raw_input("please input your word:")
word_meaning = raw_input("please input your word meaning:")
if word_dict.has_key(word):
continue
word_dict[word] =word_meaning
if command ==str(2):
word = raw_input("please input your word to find:")
if word_dict.has_key(word):
print word_dict[word]
continue
print "the word is not found!"
if command == str(3):
word = raw_input("please input your word to delete:")
if word_dict.has_key(word):
del word_dict[word]
continue
print "delete is done!"
print "word to delete is not found!"
if command == "bye":
break
word_dict = {}
help = u'''
1:add a word
2:find a word meaning
3: delete a word
input bye to exit
'''
print help
while 1:
command = raw_input("please input your command:")
if command ==str(1):
word = raw_input("please input your word:")
word_meaning = raw_input("please input your word meaning:")
if word_dict.has_key(word):
continue
word_dict[word] =word_meaning
if command ==str(2):
word = raw_input("please input your word to find:")
if word_dict.has_key(word):
print word_dict[word]
continue
print "the word is not found!"
if command == str(3):
word = raw_input("please input your word to delete:")
if word_dict.has_key(word):
del word_dict[word]
print "delete is done!"
continue
print "word to delete is not found!"
if command == "bye":
break 19、输入一个正整数,输出其阶乘结果
result=1
for i in range(1,11):
result*=i
print result 20、计算存款利息
r1=0.0035
r2=0.035
r3=0.0155
r4=0.04
deposit = 1000.0
print u"一年期活期总收益:%f" %(deposit*(1+r1))
print u"一年期定期总收益:%s" %(deposit*(1+r2))
print u"半年期定期总收益:%s" %(deposit*(0.5+r3)+deposit*(0.5+r3))
print u"2年期定期总收益:%s" %(deposit*(1+r4)) 21、输入3个数字,以逗号隔开,输出其中最大的数
答案:
num_list=num_list.split(",")
print max(num_list) 22、输入一个年份,输出是否为闰年是闰年的条件:
if (year%4==0 and year %100 !=0) or year %400==0:
print "%s is a leap year!" %year
else:
print "%s is not a leap year!" %year 23、求两个正整数m和n的最大公约数
a=20
b=10
if a
else:
c=b
result =0
for i in range(1,c+1):
if a%i ==0 and b%i ==0:
result=i
print u"%s 和 %s 的最大公约数:%s" %(a,b,result)
a=20
b=10
if a
else:
c=b
result =0
for i in range(c,0,-1):
if a%i ==0 and b%i ==0:
result=i
break
print u"%s 和 %s 的最大公约数:%s" %(a,b,result) 练习:读入一个学生的考试得分,
《60 不及格 练习:使用while 循环三次,读入三个单词,并将三个单词拼成一个句子后输出
练习:生成一个1到50的大字符串每个数字之间有个空格
for i in range(1,51,1):
if i == 50:
result = result+str(i)
result = result+str(i)+" "
print result练习:使用while统计的句子中有几个数字
练习:将一个列表元素倒序存在一个新列表中
练习:加密
encoded_letters=""
for s in letters:
if (s >= 'a' and s<"w")or(s >= 'A' and s <"W"):
encoded_letters+=chr(ord(s)+4)
elif s>="w" and s<="z":
encoded_letters+=chr(ord(s)-ord("w")+97)
elif s>="W" and s<="Z":
encoded_letters+=chr(ord(s)-ord("W")+65)
else:
print "some content is not letter!please try again!"
continue
print encoded_letters 练习:转换二进制到十进制
练习:生成所有的小写字母、大写字母和大小写混合字母
练习:判断一个句子中包含多少个字母:
>>> for s in range(65,65+26):
... letters+=chr(s)+chr(s+32)
...
>>> print letters
>>> content=raw_input("please input a sentence:")
please input a sentence:I am a boy!
>>> letter_count=0
>>> for s in content:
... if s in letters:
... letter_count+=1
...
>>> print letter_count练习:生成所有的小写字母、大写字母和大小写混合字母
练习:判断一个句子中包含多少个字母:
练习有一个长度是101的数组,存在1~100的数字,有一个是重复的,拿重复的找出来
练习2个长度相同的list,一个里面的做字典的key,另一个做value,请写个函数实现
#判断a[i]的类型是否是不变的,字典的key不能是可变元素
1、用尽可能多的方法实现liest去重
3、实现数学中多项式求和公式的打印
4、统计名字列表中,各名字的首字母在名字列表中出现的次数
5、输入三个数,判断是否能构成三角形
a,b,c=input("please input three num a,b,c:")
d=min(a,b,c)
e=max(a,b,c)
if d<=0:
print "error"
elif (a+b+c)>2*e:
print U"能组成三角形"
else:
print u"不能组成三角形"6、实现字典的fromkeys方法
能被哈希:就是唯一的,不可变的
哈希
7、键盘读入一字符串,逆序输出
用推导列表看帮助文档里是否有具体的方法
8、读入一个整数n,输出n的阶乘
9、打印1/2, 1/3, 1/4,….1/10
>>> hash("asd")
>>> a.extend([1,2])
深拷贝,对象会变,元素也会变 10.写一个函数实现一个数学公式
11.输入数字a,n,如a,4,则打印a+aa+aaa+aaaa之和
>>> "+".join((lambda n:["a"*i for i in range(1,n+1)])(4))
'a+aa+aaa+aaaa'
装饰器:
12、求100个随机数之和,随机数要求为0—9的整数
13、要求在屏幕上分别显求1到100之间奇数之和与偶数之和
闻其:
n4=re.findall(r"(\d*[02468]{1})\,",(str(range(1,101))[:-1]+","))
print (str(range(1,101))[:-1]+",")
for i in range(3,5):
print eval('reduce(lambda x,y:int(x)+int(y),n%s)' % i) 14、输入10个数,并显示最大的数与最小的数
闻其:
15、给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
闻其:
16、求1000以内的所有水仙花数
17、编程求s=1!+2!+3!+…..+n!
18、钞票换硬币把一元钞票换成一分、二分、五分硬币(每种至少一枚)有多种换法,分别有哪些?
19、自己实现在一句话中查找某个单词的算法,存在返回索引号,否则返回False
20、读入一个十进制整数,实现十进制转二进制算法将其转成二进制数要求:不能使用现成进制转换函数,自己写代码实现
小练习:读入一组数字,然后把每个数字加一后输出。比如说:123,输出之后是2、3、4
1 读入一组数据,纯数字,读入之后的类型是字符串
num = raw_input("input a number:")
2 将这个数字,拆成每个数字是个独立的元素,循环这个字符串,放到list1里
list1=[]
for i in num:
list1.append(i)
3 生成一个新的list2,存储结果
list2=[]
4 遍历list1的每一个元素,转换为数字类型,然后+1,转换为字符串类型,然后存到list2里面
for i in list1:
list2.append(str(int(i)+1))
5 这个时候List2里面存的都是字符串类型,然后拼接为最后的结果,结果也是字符串,
转化为int类型。
print int("".join(list2)) 一行代码解决:
练习:生成一个随机密码,包含大小写字母,数字定义一个函数,生成一组随机密码,要求大小写组合+数字,10位以上
import random
import string
a=list(string.uppercase)
random.shuffle(a)
print a[:4]
str1=a
2 想办法生成3个随机小写字母的字符串
import random
import string
a=list(string.lowercase)
random.shuffle(a)
print a[:3]
str2=a
3 想办法生成3个随机数字的字符串
import random
import string
a=list(string.digits)
random.shuffle(a)
print a[:3]
str3=a
4 讲前三步的结果,拼接成一个10位的字符串
result =str1+str2+str3
5 封装到一个函数里面#只有单独运行本文件时,才会执行这段代码,如果作为模块导入后,是不会运行的
11、画等(腰)边三角形(实心、空心)
向上实心三角形
向下实心三角形
空心三角形
1、打印2000-3000之间被7整除但不被5整除的数,以,(逗号)分隔
2、输出9*9口诀表
3、计算1 - 1/2 + 1/3 - 1/4 + … + 1/99 - 1/100 + …直到最后一项的绝对值小于10的-5次幂为止
4、编程将类似“China”这样的明文译成密文,密码规律是:用字母表中原来的字母后面第4个字母代替原来的字母,不能改变其大小写,如果超出了字母表最后一个字母则回退到字母表中第一个字母
5、输出以下如下规律的矩阵
6、对一个列表求和,如列表是[4, 3, 6],求和结果是[4, 7, 13],每一项的值都等与该项的值加上前一项的值
7、一个字符串 list,每个元素是 1 个 ip,输出出现次数最多的 ip
9、实现一个简易版的计算器,功能要求:加、减、乘、除,支持多数同时进行计算
10、有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和
11、画等(腰)边三角形(实心、空心)
12、画倒等边三角形
13、画直角三角形(实心、空心)
14、用*号输出字母C的图案
15、打印N,口,H图案
16、打印出如图所示的杨辉三角形,要求可以自定义行数
19、找出一段句子中最长的单词及其索引位置,以list返回
20、返回序列中的最大数
练习题1:操作一个list做增删该查操作(写一个图书管理系统)
练习题2:完成引用复制和非引用复制的一个例子
练习题3:找到两个列表中不同的元素和相同元素
练习取0-100内的奇数,存到一个list里面,偶数存到另外一个list里面
1 声明一个List存储奇数
2 声明一个list存储偶数
3 从0-100遍历每个数,判断如果可以被2整除就放到偶数列表,否则放奇数列表
4 打印两个列表的内容
#1 声明一个List存储奇数
odd_list=[]
#2 声明一个list存储偶数
even_list=[]
#3 从0-100遍历每个数,判断如果可以被2整除就放到偶数列表,否则放奇数列表
for i range(0,101):
if i %2 ==0:
even_list.append(i)
else:
odd_list.append(i)
#4 打印两个列表的内容
print #2 声明一个list存储偶数
even_list
print odd_list1.基础题:
1、匹配一行文字中的所有开头的字母内容
2、匹配一行文字中的所有开头的数字内容
3、匹配一行文字中的所有开头的数字内容或数字内容
4、只匹配包含字母和数字的行
5、写一个正则表达式,使其能同时识别下面所有的字符串:'bat', 'bit', 'but', 'hat', 'hit', 'hut‘
6、匹配所有合法的python标识符
7、提取每行中完整的年月日和时间字段
8、将每行中的电子邮件地址替换为你自己的电子邮件地址
9、匹配\home关键字:
1、使用正则提取出字符串中的单词
2、使用正则表达式匹配合法的邮件地址:
3、国际域名格式如下:
4、提取字符串中合法的超链接地址
5、统计文件中单词个数
6、写一个函数,其中用正则验证密码的强度
计算程序执行耗时
2、将时间字符串转换为时间戳
将格式时间字符串转换成时间元组,然后再转换成自定义的时间格式字符串
4、将当前时间戳转换为指定格式日期
5、创建名称为当前时间(年月日)的目录,在这个目录下创建名称为当前时间(年月日)的txt文件,并且输入内容为“你好”
6、获得三天(三小时和三分钟)前的时间方法
7、计算昨天和明天的日期
8、使用datetime模块来获取当前的日期和时间