Python练手例子(11)
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例