Python练手例子(11)
程序员文章站
2022-07-05 16:02:46
61、打印出杨辉三角形。 62、查找字符串。 63、使用Tkinter画椭圆。 64、利用ellipse 和 rectangle 画图。 65、一个最优美的图案。 66、输入3个数a,b,c,按大小顺序输出。 参考资料: Python 100例 ......
61、打印出杨辉三角形。
#python3.7 from sys import stdout 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[i][0] = 1 a[i][i] = 1 for i in range(2,10): for j in range(1,i): a[i][j] = a[i - 1][j-1] + a[i - 1][j] for i in range(10): for j in range(i + 1): stdout.write(str(a[i][j])) stdout.write(' ') print()
62、查找字符串。
#python3.7 sstr1 = 'language' sstr2 = 'age' print(sstr1.find(sstr2)) 结果: 5
63、使用tkinter画椭圆。
#python3.7 from tkinter import * if __name__ == '__main__': 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()
64、利用ellipse 和 rectangle 画图。
#python3.7 from tkinter import * if __name__ == '__main__': canvas = canvas(width = 400, height = 600, bg = 'white') left = 20 right = 50 top = 50 num = 15 for i in range(num): canvas.create_oval(250 - right, 250 - left, 250 + right, 250 + left) canvas.create_oval(250 - 20, 250 - top, 250 + 20, 250 + top) canvas.create_oval(20 - 2 * i, 20 - 2 * i, 10 * (i + 2), 10 * (i + 2)) right += 5 left += 5 top += 10 canvas.pack() mainloop()
65、一个最优美的图案。
#python3.7 from tkinter import * import math class pts: def __init__(self): self.x = 0 self.y = 0 points = [] def linetodemo(): 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()
66、输入3个数a,b,c,按大小顺序输出。
#python3.7 if __name__ == '__main__': n1 = int(input('n1 = \n')) n2 = int(input('n2 = \n')) n3 = int(input('n3 = \n')) def swap(p1, p2): return p2, p1 if n1 > n2: n1, n2 = swap(n1, n2) if n1 > n2: n1, n3 = swap(n1, n3) if n2 > n3: n2, n3 = swap(n2, n3) print(n1, n2, n3)
参考资料:
python 100例