Python 100例练手小程序--python快速上手的捷径

    xiaoxiao2022-07-06  209

    地址:https://www.runoob.com/python/python-100-examples.html

    T1:题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。

    import numpy as np data = np.array(range(1,5)) print(data) list=[] for i in data: print(i) for j in data: for t in data: if (i!=j)&(j!=t)&(t!=i):#做题时未考虑这个 list.append(i*100 +10*j +t) print(list)

    注意:if (i!=j)&(j!=t)&(t!=i):#做题时未考虑

    T2:题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。

    #!/usr/bin/python #coding:utf-8 data = int(input()) print(type(data)) if data <= 100000: data = data * (1 + 0.1) if (data > 100000) & (data <= 200000): data = 100000 * (1 + 0.1) + (data - 100000) * (1 + 0.75) if (data > 200000) & (data <= 400000): data = 100000 * (1 + 0.1) + 100000 * (1 + 0.75) + (data - 200000) * (1 + 0.05) if (data > 400000) & (data <= 600000): data = 100000 * (1 + 0.1) + 100000 * (1 + 0.75) + 200000 * (1 + 0.05) + (data - 400000) * (1 + 0.03) if (data > 600000) & (data <= 1000000): data = 100000 * (1 + 0.1) + 100000 * (1 + 0.75) + 200000 * (1 + 0.05) + 200000 * (1 + 0.03) + (data - 600000) * ( 1 + 0.015) if data > 1000000: data = 100000 * (1 + 0.1) + 100000 * (1 + 0.75) + 200000 * (1 + 0.05) + 200000 * (1 + 0.03) + 400000 * ( 1 + 0.015) + (data - 1000000) * (1 + 0.01) print(data)

    标准答案更高明:

    #!/usr/bin/python # -*- coding: UTF-8 -*- i = int(raw_input('净利润:')) arr = [1000000,600000,400000,200000,100000,0] rat = [0.01,0.015,0.03,0.05,0.075,0.1] r = 0 for idx in range(0,6): if i>arr[idx]: r+=(i-arr[idx])*rat[idx] print (i-arr[idx])*rat[idx] i=arr[idx] print r

    注意:data = input()输入的是str,需要int转化为整形

    T3: 题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

    程序分析:

    假设该数为 x。

    1、则:x + 100 = n2, x + 100 + 168 = m2

    2、计算等式:m2 - n2 = (m + n)(m - n) = 168

    3、设置: m + n = i,m - n = j,i * j =168,i 和 j 至少一个是偶数

    4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。

    5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。

    6、由于 i * j = 168, j>=2,则 1 < i < 168 / 2 + 1。

    7、接下来将 i 的所有数字循环计算即可。

    for i in range(1,85): if 168%i==0: j=168/i if i>j and (i+j)%2==0 and (i-j)%2==0: m = (i+j)/2 n = (i-j)/2 x = n*n -100 print(m,n,x)

    输出结果为:

    13.0 1.0 -99.0 17.0 11.0 21.0 23.0 19.0 261.0 43.0 41.0 1581.0

    T4: 题目:输入某年某月某日,判断这一天是这一年的第几天?

    程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:

    #coding:utf-8 year = int(input('输入年份:')) month = int(input("输入月份:")) day = int(input("输入日期:")) months = [0, 31, 59, 90, 120, 151, 181, 212, 242, 273, 303, 334] if 0<month<= 12: sum = months[month - 1] else: print("data error") sum += day leap = 0 if (year % 400==0) or ((year % 4==0) and (year % 100 != 0)): leap = 1 if (leap == 1) and (month > 2): print("2222") sum += 1 print(sum)

    输出结果:

    输入年份:2000 输入月份:2 输入日期:3 34

    T58:题目:画图,学用rectangle画方形。

    #/usr/bin/python #coding=utf-8 from tkinter import * root = Tk() root.title('Canvas') canvas = Canvas(root,width = 400,height = 400,bg = 'yellow') x0 = 200 y0 = 200 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()

    T60:题目:计算字符串长度。

    str = 'qwff' lenght = str.__len__() b = "中文" a = len('中文'.encode('utf-8')) print(len(str)) #4 print(lenght) #4 print(len(b)) #2 print(a) #6

    中文所占的字节长度是远远大于英文字符的,那为什么取len的方法完全忽视这一点呢?原因是len也好,foreach也好,都是在实际场景中使用的,人们需要的是把每个可识别的字符单独切分出来做操作,要符合人类的使用习惯。

    所以,才做成这样的。

    如果非要知道中文的字节数怎么做?

    a = len(‘中文’.encode(‘utf-8’))这个可以计算中文真实的字节数。

    另:1.计算字符串长度的方法: lenght = str.len() & len(str)

    2.#ljust(len,str)字符向左对齐,用str补齐长度 #rjust(len,str)字符向右对齐,用str补齐长度 #rjust(len,str)字符中间对齐,用str补齐长度

    print('bbb'.ljust(10,'a')) print('bbb'.rjust(10,'a')) print('bbb'.center(10,'a'))

    #zfill(width)指定字符串长度,右对齐,前面补充0

    print('bbb'.zfill(10))

    结果: bbbaaaaaaa aaaaaaabbb aaabbbaaaa 0000000bbb

    T61.题目:打印出杨辉三角形(要求打印出10行如下图)。

    #!/usr/bin/python #_*_coding:utf-8_*_ #题目:打印出杨辉三角形(要求打印出10行如下图) if __name__ == "__main__": a=[] for i in range(10): a.append([]) for j in range(10): a[i].append(0) for i in range(10): a.append(1) for j in range(i+1): a.append(1) if j>0 & j <i: a[i][j] = a[i-1][j-1] + a[i-1][j] else: a[i][j] = 1 for i in range(10): print(a[i])

    结果: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 0, 0, 0, 0, 0, 0, 0, 0] [1, 2, 1, 0, 0, 0, 0, 0, 0, 0] [1, 3, 3, 1, 0, 0, 0, 0, 0, 0] [1, 4, 6, 4, 1, 0, 0, 0, 0, 0] [1, 5, 10, 10, 5, 1, 0, 0, 0, 0] [1, 6, 15, 20, 15, 6, 1, 0, 0, 0] [1, 7, 21, 35, 35, 21, 7, 1, 0, 0] [1, 8, 28, 56, 70, 56, 28, 8, 1, 0] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

    注意:要加上这几句,提前给a列表赋值。 a=[] for i in range(10): a.append([]) for j in range(10): a[i].append(0) 这是因为:list是空的时候无法使用,要先分配元素才可以使用,不然会报错:IndexError: list index out of range 比如:

    if __name__ == "__main__": a=[] for i in range(10): a.append(1) for j in range(i+1): a.append(1) if j>0 & j <i: a[i][j] = a[i-1][j-1] + a[i-1][j] else: a[i][j] = 1 for i in range(10): print(a[i])

    报错: Traceback (most recent call last): File “C:/scratches/scratch_1.py”, line 15, in a[i][j] = 1 TypeError: ‘int’ object does not support item assignment

    T62.题目:查找字符串。

    str1 = 'abcdfgfk' str2 = 'bc' print(str1.find(str2))

    结果:

    1

    T63:题目:画椭圆。

    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()

    T93&T92:题目:时间函数举例3。

    # !/usr/bin/python # coding=utf-8 # 题目:时间函数举例3。 import time if __name__ == "__main__": start = time.clock()#当前CPU时间 t = 10000 while (t != 0): t -= 1 # time.sleep(10)#延时 end = time.clock() si = time.strftime('%Y-%m-%d %X',time.localtime(time.time()))#现在的时间 bi = time.time()#当前的时间戳(浮点型) print("The time is %6.3f" % (end - start)) print(si) print(bi)

    结果:

    The time is 0.001 2019-08-01 09:25:22 1564622722.8065605

    时间函数举例1

    #!/usr/bin/python #_*_coding:utf-8_*_ # import time print(time.strftime('%D %X',time.localtime(time.time()))) print(time.ctime(time.time())) print(time.asctime(time.localtime(time.time()))) print(time.asctime(time.gmtime(time.time())))#返回当时(0°经线位置)的时间元组

    结果:

    Fri Aug 2 09:19:51 2019 Fri Aug 2 09:19:51 2019 Fri Aug 2 01:19:51 2019

    注意: 延时的使用:time.sleep() 本地当前时间显示:1. time.strftime(’%Y-%m-%d %X’,time.localtime(time.time())) 2. import datetime print('today is: ', datetime.datetime.now()) print('today is: ', datetime.datetime.today())

    结果: today is: 2019-08-01 09:31:06.926243 today is: 2019-08-01 09:31:06.926243

    3.time.asctime最简单的时间格式 time.gmtime#返回当时(0°经线位置)的时间元组

    T94:题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。

    #!/usr/bin/python # coding=utf-8 print("Hello, World!"); # 题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。 import time import random import numpy as np # a = random.randint(0, 2 * 60) % 100 yielt = input("Do you want,to play it ,y or no\n") # x = input("请输入你猜的数字:") while (yielt == 'y'): a = random.randint(0, 10) x = int(input("请输入你猜的数字:")) start = time.clock() # a= time.time() while (a != x): if a > x: print("this nunmber is too smaller") x = int(input('请输入更大数字:')) else: print("this number is too bigger") x = int(input('请输入更小的数字:')) end = time.clock() # b = time.time() var = (end - start) /18.2 # print("It tooks you %6.3 seconds"%time.difftime(b,a)) print("It tooks you %s"%var) print("yes,you're right") print("The number is :%s" % a) yielt = input("Do you want,to play it ,y or no\n")

    结果:

    Hello, World! Do you want,to play it ,y or no y 请输入你猜的数字:5 this nunmber is too smaller 请输入更大数字:7 this nunmber is too smaller 请输入更大数字:10 It tooks you 0.7226535265582738 yes,you're right The number is :10 Do you want,to play it ,y or no

    注意: 时间函数:start = time.clock() end = time.clock()

    time.time() 是统计的wall time(即墙上时钟),也就是系统时钟的时间戳(1970纪元后经过的浮点秒数)。所以两次调用的时间差即为系统经过的总时间。 time.clock()是统计cpu时间 的工具,这在统计某一程序或函数的执行速度最为合适。两次调用time.clock()函数的插值即为程序运行的cpu时间。

    T95:题目:字符串日期转换为易读的日期格式。

    from datetime import datetime def parse_ymd(s): year_s, mon_s, day_s = s.split('-') return datetime(int(year_s), int(mon_s), int(day_s)) print(parse_ymd('2019-07-30'))

    结果:

    2019-07-30 00:00:00

    标准答案:

    #!/usr/bin/python # -*- coding: UTF-8 -*- from dateutil import parser dt = parser.parse("Aug 28 2015 12:00AM") print(dt)

    结果:

    2015-08-28 00:00:00

    T96:题目:计算字符串中子串出现的次数。

    #!/usr/bin/python #_*_coding:utf-8 _*_ if __name__=="__main__": a= input("请输入:") count={} for i in a: if i not in count: count[i]=1 else: count[i]+=1 print(count)

    结果:

    请输入:asasasdfe {'a': 3, 's': 3, 'd': 1, 'f': 1, 'e': 1}

    方法2:

    from collections import Counter res = Counter(a) print(res)

    结果:

    请输入:asdfasdd Counter({'d': 3, 'a': 2, 's': 2, 'f': 1})

    方法3:

    for character in a: count.setdefault(character,0) print(count) count[character] = count[character] +1 print(count)

    结果:

    请输入:asasdeg {'a': 0} {'a': 1, 's': 0} {'a': 1, 's': 1} {'a': 2, 's': 1} {'a': 2, 's': 2, 'd': 0} {'a': 2, 's': 2, 'd': 1, 'e': 0} {'a': 2, 's': 2, 'd': 1, 'e': 1, 'g': 0} {'a': 2, 's': 2, 'd': 1, 'e': 1, 'g': 1}

    标准答案:

    #!/usr/bin/python #_*_coding:utf-8 _*_ if __name__=="__main__": str1= input("请输入字符串:") str2= input("请输入子串:") print(str1.count(str2))

    结果:

    请输入字符串:this is a apple 请输入子串:is 2

    str.count(sub[,start[,end]]) 此方法中,各参数的具体含义如下: str:表示原字符串; sub:表示要检索的字符串; start:指定检索的起始位置,也就是从什么位置开始检测。如果不指定,默认从头开始检索; end:指定检索的终止位置,如果不指定,则表示一直检索到结尾。

    T97.题目:从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。

    #!usr/bin/python #coding=utf-8 f = open('text.txt','w') while(1): a = input('请输入: \n') if a !='#': f.write(a) else: f.close() break f1 = open("text.txt",'r') c = f1.read() print(c)

    结果:

    请输入: w 请输入: f 请输入: g 请输入: d 请输入: v 请输入: f 请输入: s 请输入: # wfgdvfs

    标准答案:

    #!/usr/bin/python #coding=utf-8 if __name__=="__main__": from sys import stdout file = input("请输入文件名:\n") f = open(file,'w') ch = input("请输入字符:\n") while ch !='#': f.write(ch) stdout.write(ch)#打印出字符 ch = input("\n") f.close() f1 = open(file,'r') ah = f1.read() print(ah)

    结果:

    请输入文件名: text.txt 请输入字符: a a b b c c d d # abcd

    注意: 1.在Python中,文件对象sys.stdin、sys.stdout和sys.stderr分别对应解释器的标准输入、标准输出和标准出错流。 以下两行代码等价:

    sys.stdout.write('hello' + '\n') print('hello') sys.stdin与input

    sys.stdin.readline( )会将标准输入全部获取,包括末尾的’\n’,因此用len计算长度时是把换行符’\n’算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符’\n’的。

    因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip(’\n’))或sys.stdin.readline( )[:-1]这两种方法去掉换行。

    T98.题目:从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。

    #!/usr/bin/python #-*- coding: UTF-8 -*- if __name__=="__main__": input=input("请输入:") input = input.upper() f = open('test.txt',"w") f.write(input) f.close() f1 = open('test.txt') in_ = f1.read() print(in_) 请输入:abcdefg ABCDEFG

    知识点: input = input.upper()小写变大写 str = str.lower()大写变小写

    print("JUST TO TEST IT".capitalize())#字符串的首字母转换成大学,其余转换成小写

    Just to test it

    print("JUST TO TEST IT".title())#字符串中所有单词的首字母转换成大学,其余转换成小写

    Just To Test It #判断字符串大小写函数:

    print("JUST TO TEST IT".isupper()) print("JUST TO TEST IT".islower()) print("Just To Test It".istitle())

    True False True

    例如:

    #!/usr/bin/python # -*- coding: UTF-8 -*- #大写变小写,小写变大写 if __name__=="__main__": input_=input("请输入:") b = [] for n in input_: if "a"<= n <="z": b.append(n.upper()) elif "A"<= n <="Z": b.append(n.lower()) else: b.append(n) print("".join(b))

    请输入:qweSDFDds QWEsdfdDS T99:题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。 注意:不加#!/usr/bin/python时, f = open(“text.txt”)没法创建txt文件

    #!/usr/bin/python #coding:utf-8 import numpy as np import os if __name__ == "__main__": f1 = open("text1.txt") a = f1.read() f1.close() print(a) f2 = open("text2.txt") b = f2.read() print(b) f2.close() c = list(a+b) # d = c.sort()#排序 d=sorted(c,reverse=False)#排序 d = "".join(d) print(d) f3 = open("text3.txt","w")#不存在文件text3.txt则创建txt文件 f3.write(d) f3.close() f3 = open("text3.txt") e = f3.read() print(e) f3.close()

    结果:

    i love you forever Are you a dog? ?Aadeeeefgilooooorrruuvvyy ?Aadeeeefgilooooorrruuvvyy

    改变下形式后的程序:

    #!/usr/bin/python #coding:utf-8 import numpy as np import os if __name__ == "__main__": with open("text1.txt") as f1: a = f1.read() print(a) f1.close() with open("text2.txt") as f2: b = f2.read() print(b) f2.close() c= list(a+b) c.sort() d="".join(c) print(d) with open("text3.txt","w") as f3: f3.write(d) f3.close() with open("text3.txt") as f: e = f.read() print(e) f.close()

    结果:

    i love you forever Are you a dog? ?Aadeeeefgilooooorrruuvvyy ?Aadeeeefgilooooorrruuvvyy

    T100.题目:列表转换为字典。 两种方法: dict(zip(a,b)) dict(d)

    #coding:utf-8 import numpy as np

    1.两个列表转为字典 a = [“q”,“w”,“e”] b = [1,2,3] c=dict(zip(a,b)) print© {‘q’: 1, ‘e’: 3, ‘w’: 2} #2.嵌套式列表转为字典 d = [[“key1”,“values1”],[“key2”,“values2”],[“key3”,“values3”]] print(dict(d)) {‘key2’: ‘values2’, ‘key3’: ‘values3’, ‘key1’: ‘values1’}

    知识点:

    #3.字符串转列表>>>str->list list(str) str.split()

    str1 = “12345” list1 = list(str1) print(“list1:”,list1)

    str2 = “123 werr wetr” list2 = str2.split() print(“list2:”,list2)

    str3 = “www.baidu.com” list3 = str3.split(".") print(“list3:”,list3)

    list1: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’] list2: [‘123’, ‘werr’, ‘wetr’] list3: [‘www’, ‘baidu’, ‘com’] #4. 列表转字符串>>>>list->str str = “”.join(list)—相当于将列表拼接为一个字符串 str(s_list) 只是将列表中的每个元素都转为字符串。

    str4 = “”.join(list3) print(“str4:”,str4) str5 = " ".join(list3) print(“str5:”,str5) str6 = “.”.join(list3) print(“str6:”,str6)

    str4: wwwbaiducom str5: www baidu com str6: www.baidu.com

    #将列表里的每个元素都转为字符串 str0 = [1,2,3,4] str7 = [str(item) for item in str0] print(“str7:”,str7) str7: [‘1’, ‘2’, ‘3’, ‘4’]

    """python反转列表的三种方式""" #1.反向输出列表-内建函数reversed() #采用list(reversed(li))-注意:reversed()函数返回的是一个迭代器,而不是一个List,所以需要list函数转换一下

    li =[1, 2, 3, 4, 5, 6] a = list(reversed(li)) print (a)

    #2.内建函数sorted() #注意:sorted()按降序排列,对于反转内容不是顺序排列的无效果,此处待改善。

    a =[1,2,3,4,5,6,7,8] c = sorted(a,reverse = True) print©

    “”“iterable – 可迭代对象。 cmp – 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。 key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。 reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。 返回值 返回重新排序的列表。”""

    #3: 使用分片

    a = [1,2,3,4,5,6,7,8] d = a[::-1] print(d)

    “”“反转字符串的方法”""

    #reverse()函数将列表的内容进行了反转, #借助这个特性,可以先将字符串转换成列表,利用reverse()函数进行反转后,再处理成字符串。 b = 12345 c = list(str(b)) c.reverse() print( c ) [‘5’, ‘4’, ‘3’, ‘2’, ‘1’]

    e = sorted(c,reverse=True) print(e) [‘5’, ‘4’, ‘3’, ‘2’, ‘1’]

    “”“list、tuple(元组)、str之间的相互转换”""

    list()方法是把字符串str或元组转成数组 tuple()方法是把字符串str或数组转成元组

    s = "abcdef" x = list(s)#字符s转列表x print(x) print(type(x))

    [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] <class ‘list’>

    y = tuple(s)#字符s转成元组y print(y) print(type(y)) print("-"*100)

    (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’) <class ‘tuple’>

    w = tuple(x) #列表x转元组w print(w) print(type(w)) print("+"*100)

    (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’) <class ‘tuple’>

    z = list(w)#元组w转成列表z print(z) print(type(z))

    [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] <class ‘list’>

    #列表和元组转换为字符串则必须依靠join函数

    n = "".join(tuple(s)) print(n) print(type(n))

    abcdef <class ‘str’>

    m = "".join(list(s)) print(m) print(type(m))

    abcdef <class ‘str’>

    p = str(tuple(s)) q = str(list(s)) print(p) print(q)

    (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’) [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

    注意:str是将元组和列表里的每个元素都转为字符串

    最新回复(0)