python提升41-60

41.模仿静态变量的用法。
class foo:
  def __init__(self, n=0):
    self.n = n
  def __call__(self, i):
    self.n += i
    return self.n
a=foo()
print a(1)
print a(2)
print a(3)
print a(4)

42.学习使用auto定义变量的用法。     略

43.模仿静态变量(static)另一案例。      略

44.两个矩阵相加
import numpy as np

x = np.array( [[12,7,3],
               [4 ,5,6],
               [7 ,8,9]])
y = np.array( [[5,8,1],
               [6,7,3],
               [4,5,9]])

z = x+y
print z

45.统计 1100 之和。
sum = 0
for i in range(1,101):
    sum += i
print sum

46.求输入数字的平方,如果平方运算后小于 50 则退出。
while(1):
    n=input('请输入一个数字:')
    print '运算结果为: %d' % (n**2)
    if n**2 < 50:
        quit()
47.两个变量值互换。
def exchange(a,b):
    a, b = b, a
    return a,b
if __name__== '__main__':
    x = 10
    y = 20
print exchange(x,y)

48.数字比较。     略

49.使用lambda来创建匿名函数。
h = lambda x, y, z: x**2 + y**3 + z**4
print h(1,2,3)

50.使用 random 模块。
import random as rd
print rd.random()
print rd.randint(10, 20)
print rd.uniform(10, 20)

51.学习使用按位与 & 。
if __name__ == '__main__':
    a = 077
    b = a & 3     #都转成二进制之后进行与操作
    print 'a & b = %d' % b
    b &= 7
    print 'a & b = %d' % b

52.学习使用按位或 |
if __name__ == '__main__':
    a = 077
    b = a | 3
    print 'a | b is %d' % b
    b |= 7
    print 'a | b is %d' % b

53.学习使用按位异或 ^ 。
if __name__ == '__main__':
    a = 077
    b = a ^ 3
    print 'The a ^ 3 = %d' % b
    b ^= 7
    print 'The a ^ b = %d' % b

54.取一个整数a从右端开始的47位。
if __name__ == '__main__':
    a = int(raw_input('input a number:\n'))
    b = a >> 4
    c = ~(~0 << 4)
    d = b & c
    print '%o\t%o' %(a,d)

55.学习使用按位取反~。
if __name__ == '__main__':
    a = 234
    b = ~a
    print 'The a\'s 1 complement is %d' % b
    a = ~a
    print 'The a\'s 2 complement is %d' % a



56.画图,学用circle画圆形。   
if __name__ == '__main__':
    import turtle

    turtle.title("画圆")
    turtle.setup(800, 600, 0, 0)
    pen = turtle.Turtle()
    pen.color("yellow")
    pen.width(5)
    pen.shape("turtle")
    pen.speed(5)
    pen.circle(100)

57.画图,学用line画直线。
from Tkinter import *
canvas=Canvas(width=300,height=300,bg='white')
canvas.pack(expand=YES, fill=BOTH)
x1,y1=50,20
x2,y2=100,20
x3,y3=75,40
x4,y4=75,100
canvas.create_line(x1,y1,x3,y3, width=3, fill='red')
canvas.create_line(x2,y2,x3,y3, width=3, fill='red')
canvas.create_line(x1,y1,x4,y4, width=3, fill='red')
canvas.create_line(x2,y2,x4,y4, width=3, fill='red')
mainloop()

58.画图,学用rectangle画方形
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()

59.画图,综合例子。略

60.计算字符串长度。 
sStr1 = 'strlen'
print len(sStr1)

猜你喜欢

转载自blog.csdn.net/dingming001/article/details/80288737
41