Python语法学习

#!/user/bin/env python3
#print(100+200+300)
#print("Hello World", "AAA", "BBBB")
#name = input()
#print("name=", name)
#print("1024 * 768 =", 1024 * 768)
#print absolute value of an integer
#a = 100
#if a >= 0:
#    print(a)
#else:
#    print(-a)
#print('I\'m \"OK\"')
#print('I\'m learning\nPython.')
#print('\\\n\\')
#print('\\\t\\')
#print('''line1
#line2
#line3'''
#)
#输出结果
#line1
#line2
#line3
#print(r'''hello,\n
#world''')
#输出结果
#hello,\n
#world
#print('''hello,\n
#world''')
#输出结果
#hello,
#
#world
#a = 123 #a 是整数
#print(a)
#a = 'ABC' #a变为字符串
#print(a)
#a = True
#print(a)
#x = 10
#x = x + 2
#print(x)
#输出结果
#12
#a='ABC'
#b=a
#print(a)
#print(b)
#a='XYZ'
#print(a)
#print(b)
#输出结果
#ABC
#ABC
#XYZ
#ABC
#a=10/3
#print(a)
#a=9/3
#print(a)
#a=10//3
#print(a)
#a=9//3
#print(a)
#a=10%3
#print(a)
#输出结果
#3.3333333333333335
#3.0
#3
#3
#1
#f = 456.789
#print(f)
#s1='Hello,world'
#print(s1)
#s2='Hello,\'Adam\''
#print(s2)
#s3=r'Hello,"Bart"'
#print(s3)
#s4=r'''Hello,
#Lisa!'''
#print(s4)
#s5='''Hello,
#Lisa!'''
#print(s5)
#s6=r'''Hello,\n
#Lisa!'''
#print(s6)
#s7='''Hello,\n
#Lisa!'''
#print(s7)
#输出结果
#456.789
#Hello,world
#Hello,'Adam'
#Hello,"Bart"
#Hello,
#Lisa!
#Hello,
#Lisa!
#Hello,\n
#Lisa!
#Hello,
#
#Lisa!
#-------------------------
#print('包含中文的str')
#a=ord('A')
#print(a)
#a=ord('中')
#print(a)
#b=chr(66)
#print(b)
#b=chr(25991)
#print(b)
#c='\u4e2d\u6587'
#print(c)
#输出结果
#包含中文的str
#65
#20013
#B
#文
#中文
#-------------------------
#x=b'ABC'
#print(x)
#x='ABC'.encode('ascii')
#print(x)
#x='中文'.encode('utf-8')
#print(x)
##x='中文'.encode('ascii')
##报错了:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
#x=b'ABC'.decode('ascii')
#print(x)
#x=b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
#print(x)
#x=b'\xe4\xb8\xad\xff'.decode('utf-8')
##报错了:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 3: invalid start byte
#x=b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
#print(x)
#x=len('ABC')
#print(x)
#x=len('中文')
#print(x)
#x=len(b'ABC')
#print(x)
#x=len(b'\xe4\xb8\xad\xe6\x96\x87')
#print(x)
#x=len('中文'.encode('utf-8'))
#print(x)
##输出结果
#b'ABC'
#b'ABC'
#b'\xe4\xb8\xad\xe6\x96\x87'
#ABC
#中文
#中
#3
#2
#3
#6
#6
#-------------------------
#x='Hello,%s' % 'world'
#print(x)
#x='Hi, %s, you have $%d.' % ('Michael', 1000000)
#print(x)
#x='%2d-%02d' % (3,1)
#print(x)
#x='%.2f' % 3.1415926
#print(x)
#x='Age: %s. Gender: %s' % (25, True)
#print(x)
#x='growth rate: %d %%' % 7
##x='growth rate: %d %' % 7 #这个会报错:ValueError: incomplete format
#print(x)
#x='Hello, {0}, 成绩提升了 {1:.1f}%%'.format('小明', 17.125)
#print(x)
#输出结果
#Hello,world
#Hi, Michael, you have $1000000.
# 3-01
#3.14
#Age: 25. Gender: True
#growth rate: 7 %
#Hello, 小明, 成绩提升了 17.1%%
#-------------------------
#classmates=['Michael','Bob','Tracy']
#print(classmates)
#x=len(classmates)
#print(x)
#x=classmates[0]
#print(x)
#x=classmates[1]
#print(x)
#x=classmates[2]
#print(x)
##x=classmates[3] #这个会报错:IndexError: list index out of range
#x=classmates[-1]
#print(x)
#x=classmates[-2]
#print(x)
#x=classmates[-3]
#print(x)
##x=classmates[-4] #这个会报错:IndexError: list index out of range
#classmates.append('Adam')
#print(classmates)
#classmates.insert(1, 'Jack')
#print(classmates)
#classmates.pop()
#print(classmates)
#classmates.pop(1)
#print(classmates)
#classmates[1]='Sarah'
#print(classmates)
#L=['Apple',123,True]
#print(L)
#s=['python','java',['asp','php'],'scheme']
#print(s)
#a=len(s)
#print(a)
#p=['asp','php']
#s=['python','java',p,'scheme']
#x=p[1]
#print(x)
#x=s[2][1]
#print(x)
#L=[]
#a=len(L)
#print(a)
#classmates=('Michael','Bob','Tracy')
#print(classmates)
##classmates[0]="AA" #这个会报错:TypeError: 'tuple' object does not support item assignment
#t=()
#print(t)
#t=(1,2)
#print(t)
#t=(1) #这个表示数学上的小括号,数字1
#print(t)
#t=(1,)#这个表示是一个python的tuple元组,只有一个元素也要加逗号
#print(t)
##t[0]=5 #这个会报错:占位后也不能赋值啊 TypeError: 'tuple' object does not support item assignment
#t=('a','b',['A','B'])
#print(t)
#t[2][0]='X'
#t[2][1]='Y'
#print(t)
##输出结果
#['Michael', 'Bob', 'Tracy']
#3
#Michael
#Bob
#Tracy
#Tracy
#Bob
#Michael
#['Michael', 'Bob', 'Tracy', 'Adam']
#['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
#['Michael', 'Jack', 'Bob', 'Tracy']
#['Michael', 'Bob', 'Tracy']
#['Michael', 'Sarah', 'Tracy']
#['Apple', 123, True]
#['python', 'java', ['asp', 'php'], 'scheme']
#4
#php
#php
#0
#('Michael', 'Bob', 'Tracy')
#()
#(1, 2)
#1
#(1,)
#('a', 'b', ['A', 'B'])
#('a', 'b', ['X', 'Y'])
#-------------------------

#age=20
#if age >=18:
#    print('your age is', age)
#    print('adult')
#age=3
#if age >=18:
#    print('your age is', age)
#    print('adult')
#else:         # 这个会报错:SyntaxError: invalid syntax
#    print('your age is', age)
#    print('teenager') #这个会报错:Tab键不一定是4个空格,还是老老实实打4个空格吧  TabError: inconsistent use of tabs and spaces in indentation
#age=3
#if age >=18:
#    print('adult')
#elif age >=6:
#    print('teenager')
##else:
##print('kid') #这个会报错 else 下边的函数体要有4格缩进啊 IndentationError: expected an indented block
#else:
#    print('kid')
#s=input('birth: ')
#birth=int(s) #这个会报错 如果你输入的是个数字不用int强转,下边和2000比较,就会报错 TypeError: '<' not supported between instances of 'str' and 'int'
### 如果你输入的是个字符串,又用int强转了, 就会报错 ValueError: invalid literal for int() with base 10: 'abc'
#if birth<2000: 
#    print('00前')
#else:
#    print('00后')
#print("体质指数(BMI)=体重(kg)÷身高^2(m)")
#name=input('请输入你的名字:')
#height=float(input('请输入你的身高(米):'))
#weight=float(input('请输入你的体重(千克):'))
#bmi=weight/(height*height)
#a=bmi
#if a>=32:
#    print('你好: ',name,' 你的bmi指数是:%.2f '%bmi,'  属于严重肥胖')
#elif a>=28:
#    print('你好: ',name,' 你的bmi指数是:%.2f '%bmi,'  属于肥胖')
#elif a>=25:
#    print('你好: ',name,' 你的bmi指数是:%.2f '%bmi,'  属于过重')
#elif a>=18.5:    
#    print('你好: ',name,' 你的bmi指数是:%.2f '%bmi,'  属于正常')
#else:
#    print('你好: ',name,' 你的bmi指数是:%.2f '%bmi,'  属于过轻')
##输出结果
#your age is 20
#adult
#your age is 3
#teenager
#kid
#birth: 1982
#00前
#体质指数(BMI)=体重(kg)÷身高^2(m)
#请输入你的名字:ABC
#请输入你的身高(米):1.73
#请输入你的体重(千克):75
#你好:  ABC  你的bmi指数是:25.06    属于过重
#-------------------------
#names=['Michael','Bob','Tracy']
#for name in names:
#    print(name)
#sum=0
#for x in [1,2,3,4,5,6,7,8,9,10]:
#    sum+=x #这个和 sum=sum+x一样正常运行
#print(sum)
#x=list(range(5))
#print(x)
#sum=0
#n=99
#while n>0:
#    sum=sum+n
#    n=n-2
#print(sum)
#n=1
#while n<=100:
#    if n>10:
#        break
#    print(n)
#    n=n+1
#print('END')
#n=0
#while n<10:
#    n=n+1
#    if n % 2==0:
#        continue
#    print(n)
##输出结果
#Michael
#Bob
#Tracy
#55
#[0, 1, 2, 3, 4]
#2500
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#END
#1
#3
#5
#7
#9
#-------------------------
#d={'Michael':95,'Bob':75,'Tracy':85}
#print(d['Michael'])
#d['Adam']=67
#print(d['Adam'])
#d['Jack']=90
#print(d['Jack'])
#d['Jack']=88
#print(d['Jack'])
##d['Tomas'] # 这个会报错: KeyError: 'Tomas'
#x='Tomas' in d
#print(x)
#x=d.get('Thomas')
#print(x)
#x=d.get('Thomas',-1)
#print(x)
#x=d.pop('Bob')
#print(x)
#print(d)
#key=[1,2,3]
##d[key]='a list' # 这个会报错:TypeError: unhashable type: 'list'
#s=set([1,2,3])
#print(s)
#s=set([4,4,5,5,6,6])
#print(s)
#s.add(7)
#print(s)
#s.add(6)
#print(s)
#s.remove(4)
#print(s)
#s1=set([1,2,3])
#s2=set([2,3,4])
#x=s1&s2
#print(x)
#y=s1|s2
#print(y)
#key=[1,2,3]
##s.add(key) # 这个会报错: TypeError: unhashable type: 'list'
#a=['c','b','a']
#print(a)
#a.sort()
#print(a)
#a='abc'
#b=a.replace('a','A')
#print(a)
#print(b)
##输出结果
#95
#67
#90
#88
#False
#None
#-1
#75
#{'Michael': 95, 'Tracy': 85, 'Adam': 67, 'Jack': 88}
#{1, 2, 3}
#{4, 5, 6}
#{4, 5, 6, 7}
#{4, 5, 6, 7}
#{5, 6, 7}
#{2, 3}
#{1, 2, 3, 4}
#['c', 'b', 'a']
#['a', 'b', 'c']
#abc
#Abc
#-------------------------
#x=abs(100)
#print(x)
#x=abs(-20)
#print(x)
#x=abs(12.34)
#print(x)
##abs(1,2) # 这个会报错:TypeError: abs() takes exactly one argument (2 given)
##abs('a') # 这个会报错:TypeError: bad operand type for abs(): 'str'
#x=max(1,2)
#print(x)
#x=max(2,3,1,-5)
#print(x)
#x=int('123')
#print(x)
#x=int(12.34)
#print(x)
#x=str(1.23)
#print(x)
#x=str(100)
#print(x)
#x=bool(1)
#print(x)
#x=bool('')
#print(x)
#a=abs
#x=a(-1)
#print(x)
##输出结果
#100
#20
#12.34
#2
#3
#123
#12
#1.23
#100
#True
#False
#1
#-------------------------
#def my_abs(x):
#    if x>=0:
#        return x
#    else:
#        return -x
#print(my_abs(-99))
#def nop():
#    pass
#age=1
#if age>=18:
#    pass
##my_abs(1,2) # 这个会报错 TypeError: my_abs() takes 1 positional argument but 2 were given
##my_abs('A') # 这个会报错 TypeError: '>=' not supported between instances of 'str' and 'int'
#def my_abs(x):
#    if not isinstance(x,(int,float)):
#        raise TypeError('TMD bad operand type')
#    if x>=0:
#        return x
#    else:
#        return -x
##my_abs('A') # 这个会报错 TypeError: TMD bad operand type
#import math
#def move(x,y,step,angle=0):
#    nx=x+step*math.cos(angle)
#    ny=y-step*math.sin(angle)
#    return nx,ny
#x,y=move(100,100,60,math.pi/6)
#print(x,y)
#r=move(100,100,60,math.pi/6)
#print(r)
#x=math.sqrt(2)
#print(x)
##输出结果
#99
#151.96152422706632 70.0
#(151.96152422706632, 70.0)
#-------------------------
#def power(x):
#    return x*x
#print(power(5))
#print(power(15))
#def power(x, n=2):
#    s=1
#    while n>0:
#        n=n-1
#        s=s*x
#    return s
#print(power(5,2))
#print(power(5,3))
#def enroll(name,gender,age=6,city='Beijing'):
#    print('name',name)
#    print('gender',gender)
#    print('age',age)
#    print('city',city)
#enroll('Sarah','F')
#enroll('Bob','M',7)
#x=enroll('Adam','M',city='Tianjin')
#print(x)
#def add_end(L=[]):
#    L.append('END')
#    return L
#print(add_end([1,2,3]))
#print(add_end(['x','y','z']))
#print(add_end())
#print(add_end())
#def add_end(L=None):
#    if L is None:
#        L=[]
#    L.append('END')
#    return L
#print(add_end())
#print(add_end())
#def calc(numbers):
#    sum=0
#    for n in numbers:
#        sum=sum+n*n
#    return sum
#print(calc([1,2,3]))
#print(calc([1,3,5,7]))
#def calc(*numbers):
#    sum=0
#    for n in numbers:
#        sum=sum+n*n
#    return sum
#print(calc(1,2,3))
#print(calc(1,3,5,7))
#print(calc(1,2))
#print(calc())
#nums=[1,2,3]
#print(calc(nums[0],nums[1],nums[2]))
#print(*nums)
#print(nums)
#print(calc(*nums))
##输出结果
#25
#225
#25
#125
#name Sarah
#gender F
#age 6
#city Beijing
#name Bob
#gender M
#age 7
#city Beijing
#name Adam
#gender M
#age 6
#city Tianjin
#None
#[1, 2, 3, 'END']
#['x', 'y', 'z', 'END']
#['END']
#['END', 'END']
#['END']
#['END']
#14
#84
#14
#84
#5
#0
#14
#1 2 3
#[1, 2, 3]
#14
#------------==============-------------
#def person(name,age,**kw):
#    print('name:',name,'age:',age,'others:',kw)
#person('Michael',30)
#person('Bob',35,city='Beijing')
#person('Adam',45,gender='M',job='Engineer')
#extra={'city':'Beijing','job':'Engineer'}
#person('Jack',24,city=extra['city'],job=extra['job'])
#person('Jack',24,**extra)
#def person(name,age,**kw):
#    if'city' in kw:
#        #有city参数
#        pass
#    if'job'in kw:
#        #有job参数
#        pass
#    print('name:',name,'age:',age,'others:',kw)
#person('Jack',24,city='Beijing',addr='Chaoyang',zipcode=123456)
#def person(name,age,*,city,job):
#    print(name,age,city,job)
#print(person('Jack', 24, city='Beijing', job='Engineer'))
##print(person('Jack', 24, 'Beijing', 'Engineer')) #这个会报错 TypeError: person() takes 2 positional
## arguments but 4 were given
##print(person('Jack', 24, city='Beijing', job='Engineer',addr='Chaoyang')) #这个会报错 --
##这个会报错 #TypeError: person() got an unexpected keyword argument 'addr'
#def person(name,age, *args,city,job):
#    print(name,age,args,city,job)
##person('Jack',24,'Beijing','Engineer') #这个会报错--
##这个会报错 #TypeError: person() missing 2 required keyword-only arguments: 'city' and 'job'
#person('Jack',24,city='Beijing',job='Engineer')
#def person(name,age, *,city='Beijing',job):
#    print(name,age,city,job)
#person('Jack',23,job='Engineer')
#def f1(a,b,c=0,*args,**kw):
#    print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw)
#def f2(a,b,c=0,*,d,**kw):
#    print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
#f1(1,2)
#f1(1,2,c=3)
#f1(1,2,3,'a','b')
#f1(1,2,3,'a','b',x=99)
#f2(1,2,d=99,ext=None)
#args=(1,2,3,4)
#kw={'d':99,'x':'#'}
#f1(*args,**kw)
#args=(1,2,3)
#kw={'d':88,'x':'#'}
#f2(*args,**kw)
##输出结果
#name: Michael age: 30 others: {}
#name: Bob age: 35 others: {'city': 'Beijing'}
#name: Adam age: 45 others: {'gender': 'M', 'job': 'Engineer'}
#name: Jack age: 24 others: {'city': 'Beijing', 'job': 'Engineer'}
#name: Jack age: 24 others: {'city': 'Beijing', 'job': 'Engineer'}
#name: Jack age: 24 others: {'city': 'Beijing', 'addr': 'Chaoyang', 'zipcode': 12
#3456}
#Jack 24 Beijing Engineer
#None
#Jack 24 () Beijing Engineer
#Jack 23 Beijing Engineer
#a= 1 b= 2 c= 0 args= () kw= {}
#a= 1 b= 2 c= 3 args= () kw= {}
#a= 1 b= 2 c= 3 args= ('a', 'b') kw= {}
#a= 1 b= 2 c= 3 args= ('a', 'b') kw= {'x': 99}
#a= 1 b= 2 c= 0 d= 99 kw= {'ext': None}
#a= 1 b= 2 c= 3 args= (4,) kw= {'d': 99, 'x': '#'}
#a= 1 b= 2 c= 3 d= 88 kw= {'x': '#'}
#-------------------------
#def fact(n):
#    if n==1:
#        return 1
#    return n*fact(n-1)
#print(fact(1))
#print(fact(5))
#print(fact(100))
##print(fact(1000)) #这个会报错--
##这个会报错 RecursionError: maximum recursion depth exceeded in comparison
#def fact(n):
#    return fact_iter(n,1)
#def fact_iter(num,product):
#    if num==1:
#        return product
#    return fact_iter(num-1,num*product)
#print(fact(5))
##print(fact(1000)) #这个会报错--
##这个会报错 Python解释器没有针对尾递归做优化,也会导致栈溢出。
# 利用递归函数计算阶乘
# N! = 1 * 2 * 3 * ... * N
#def fact(n):
#    if n == 1:
#        return 1
#    return n * fact(n-1)

#print('fact(1) =', fact(1))
#print('fact(5) =', fact(5))
#print('fact(10) =', fact(10))

## 利用递归函数移动汉诺塔:
#def move(n, a, b, c):
#    if n == 1:
#        print('move', a, '-->', c)
#    else:
#        move(n-1, a, c, b)
#        move(1, a, b, c)
#        move(n-1, b, a, c)

#move(4, 'A', 'B', 'C')
##输出结果
#1
#120
#93326215443944152681699238856266700490715968264381621468592963895217599993229915
#608941463976156518286253697920827223758251185210916864000000000000000000000000
#120
#fact(1) = 1
#fact(5) = 120
#fact(10) = 3628800
#move A --> B
#move A --> C
#move B --> C
#move A --> B
#move C --> A
#move C --> B
#move A --> B
#move A --> C
#move B --> C
#move B --> A
#move C --> A
#move B --> C
#move A --> B
#move A --> C
#move B --> C
#-------------------------
#L=[]
#n=1
#while n<=9:
#    L.append(n)
#    n=n+2
#print(L)
#r=[]
#n=3
#for i in range(n):
#    r.append(L[i])
#print(r)
#print(L[0:3])
#print(L[:3])
#print(L[1:3])
#print(L[-2:])
#print(L[-2:-1])
#L=list(range(50))
#print(L)
#print(L[:10])
#print(L[-10:])
#print(L[10:20])
#print(L[:10:2])
#print(L[:9:2])
#print(L[::5])
#print(L[:])
#x=(0,1,2,3,4,5)[:3]
#print(x)
#x='ABCDEFG'[:3]
#print(x)
#x='ABCDEFG'[::2]
#print(x)
##利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
#def my_trim(s):
#    while s[:1]==' ':
#        s=s[1:]
#    while s[-1:]==' ':
#        s=s[:-1]
#    return s
#x='  字符串trim   '
#print(len(x))#.decode('utf-8')
#y=my_trim('  字符串trim   ')
#print(y)
#print(len(y))#.decode('utf-8')
##输出结果
#[1, 3, 5, 7, 9]
#[1, 3, 5]
#[1, 3, 5]
#[1, 3, 5]
#[3, 5]
#[7, 9]
#[7]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
#2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
#2, 43, 44, 45, 46, 47, 48, 49]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
#[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
#[0, 2, 4, 6, 8]
#[0, 2, 4, 6, 8]
#[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
#2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
#2, 43, 44, 45, 46, 47, 48, 49]
#(0, 1, 2)
#ABC
#ACEG
#12
#字符串trim
#7
#-------------------------

#d={'a':1,'b':2,'c':3}
#for key in d:
#    print('key',key)
#for value in d.values():
#    print('value',value)
#for k,v in d.items():
#    print("k=",k,' v=',v)
#for ch in 'ABC':
#    print('ch',ch)
#from collections import Iterable
#print(isinstance('abc',Iterable))
#print(isinstance(5,Iterable))
#print(isinstance('5',Iterable))
#for k,v in enumerate(['A','B','C']):
#    print(k,v)
#for k,v in enumerate(('D','E','F')):
#    print(k,v)
#for x,y in [(1,1),(2,4),(3,9)]:
#    print(x,y)
##使用迭代查找一个list中最小和最大值,并返回一个tuple
#def findMinAndMax(L):
#    if L==None: #
#        return(None,None)
#    if L==[]:
#        return(None,None)
#    else:
#        min=max=L[0]
#        for i in L:
#            if min>i:
#                min=i
#            if max<i:
#                max=i
#        return (min,max)
#print(findMinAndMax((5,4,6)))  
#print(findMinAndMax([]))
#print(findMinAndMax(None))
#print(findMinAndMax([15,24,36]))
##输出结果
#key a
#key b
#key c
#value 1
#value 2
#value 3
#k= a  v= 1
#k= b  v= 2
#k= c  v= 3
#ch A
#ch B
#ch C
#calc.py:851: DeprecationWarning: Using or importing the ABCs from 'collections'
#instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
#
#  from collections import Iterable
#True
#False
#True
#0 A
#1 B
#2 C
#0 D
#1 E
#2 F
#1 1
#2 4
#3 9
#(4, 6)
#(None, None)
#(None, None)
#(15, 36)

#-------------------------

#print(list(range(1,11)))
#L=[]
#for x in range(1,11):
#    L.append(x*x)
#print(L)
#a=[x*x for x in range(1,11)]
#print(a)
#a=[x*x for x in range(1,11) if x%2==0]
#print(a)
#a=[m+n for m in 'ABC' for n in 'XYZ']
#print(a)
#import os
#a=[d for d in os.listdir('.')]
#print(a)
#d={'x':'A','y':'B','z':'C'}
#for k,v in d.items():
#    print(k,' = ', v)
#a=[k+' = '+v for k,v in d.items()]
#print(a)
#L=['Hello', 'World', 'IBM', 'Apple']
#a=[s.lower() for s in L]
#print(a)
#L=['Hello', 'World', 18, 'IBM', 'Apple']
#L2=[x.lower() if isinstance(x,str) else x for x in L]
#print(L2)
##输出结果
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#[4, 16, 36, 64, 100]
#['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
#['calc.py']
#x  =  A
#y  =  B
#z  =  C
#['x = A', 'y = B', 'z = C']
#['hello', 'world', 'ibm', 'apple']
#['hello', 'world', 18, 'ibm', 'apple']
#-------------------------
#L=[x*x for x in range(4)]
#print(L)
#g=(x*x for x in range(4))
#print(g)
#print(next(g))
#print(next(g))
#print(next(g))
#print(next(g))
##print(next(g)) # 这个会报错 StopIteration
#g=(x*x for x in range(4))
#for n in g:
#    print("n=",n)
#def fib(max):
#    n,a,b=0,0,1
#    while n<max:
#        print(b)
#        a,b=b,a+b
#        n=n+1
#    return 'done'
#fib(6)
#def fib(max):
#    n,a,b=0,0,1
#    while n<max:
#        yield b
#        a,b=b,a+b
#        n=n+1
#    return 'done'
#f=fib(6)
#print(f)
#for n in f:
#    print(n)
#g=fib(6)
#while True:
#    try:
#        x=next(g)
#        print('g=',x)
#    except StopIteration as e:
#        print('Generator return value:',e.value)
#        break
#def odd():
#    print('step 1')
#    yield 1
#    print('step 2')
#    yield(3)
#    print('step 3')
#    yield(5)
#o=odd()
#next(o)
#next(o)
#next(o)
##next(o) # 这个会报错 StopIteration
## 传统的杨辉三角形实现
#def pascal(row):
#    result_list = [0] * (row * 2 + 1)

#    for row_loc in range(row):
#        base_loc = row - row_loc - 1
#        if row_loc == 0:
#            result_list[base_loc] = 1
#        else:
#            result_list[base_loc] = result_list[base_loc + 1]
#            for line_loc in range(row_loc):
#                now_loc = base_loc + (line_loc + 1) * 2
#                result_list[now_loc] = result_list[now_loc - 1] + result_list[now_loc + 1]
#                result_list[now_loc - 1] = 0

#        print(str(result_list).replace("]", ",").replace(" 0,", "  ").replace(",", "").replace("[0", "  ").replace("[", " "))

#pascal(10)
## 利用python列表迭代的实现
#def printLine(lineList,row):
#    lineList = [str(tmpNum) for tmpNum in lineList]
#    print("%s%s" % (" " * (row - len(lineList)), " ".join(lineList)))

#def pascal(row):
#    for i in range(row):
#        if i < 2:
#            yhList = [1] * (i + 1)
#        else:
#            yhList[1:-1] = [(tmpNum + yhList[j])  for j, tmpNum in enumerate(yhList[1:])]
#        printLine(yhList,row)

#pascal(10)
## 基于函数式编程思路的实现
#from functools import reduce
#def row(x):
#    return ' '.join(list(map(str,reduce(lambda x,y:list(map(sum,zip([0]+x,x+[0]))),range(x),[1]))))
#def pascal(x):
#    return '\n'.join(row(i).center(len(row(x-1))) for i in range(x))
#print(pascal(10))
##输出结果
#[0, 1, 4, 9]
#<generator object <genexpr> at 0x00724E70>
#0
#1
#4
#9
#n= 0
#n= 1
#n= 4
#n= 9
#1
#1
#2
#3
#5
#8
#<generator object fib at 0x00724E70>
#1
#1
#2
#3
#5
#8
#g= 1
#g= 1
#g= 2
#g= 3
#g= 5
#g= 8
#Generator return value: done
#step 1
#step 2
#step 3
#                   1
#                 1   1
#               1   2   1
#             1   3   3   1
#           1   4   6   4   1
#         1   5   10   10   5   1
#       1   6   15   20   15   6   1
#     1   7   21   35   35   21   7   1
#   1   8   28   56   70   56   28   8   1
# 1   9   36   84   126   126   84   36   9   1
#         1
#        1 1
#       1 2 1
#      1 3 3 1
#     1 4 6 4 1
#    1 5 10 10 5 1
#   1 6 15 20 15 6 1
#  1 7 21 35 35 21 7 1
# 1 8 28 56 70 56 28 8 1
#1 9 36 84 126 126 84 36 9 1
#             1
#            1 1
#           1 2 1
#          1 3 3 1
#         1 4 6 4 1
#       1 5 10 10 5 1
#      1 6 15 20 15 6 1
#    1 7 21 35 35 21 7 1
#   1 8 28 56 70 56 28 8 1
#1 9 36 84 126 126 84 36 9 1
#-------------------------
#from collections import Iterable
#print(isinstance([],Iterable))
#print(isinstance({},Iterable))
#print(isinstance('abc',Iterable))
#print(isinstance((x for x in range(10)),Iterable))
#print(isinstance(100,Iterable))
#from collections import Iterator
#print(isinstance((x for x in range(10)),Iterator))
#print(isinstance([],Iterator))
#print(isinstance({},Iterator))
#print(isinstance('abc',Iterator))
#print(iter([]),Iterator)
#print(iter({}),Iterator)
#print(iter('abc'),Iterator)
#print(iter((x for x in range(10))),Iterator)
##print(iter(100),Iterator) #这个会报错 TypeError: 'int' object is not iterable
##输出结果
#calc.py:1109: DeprecationWarning: Using or importing the ABCs from 'collections'
# instead of from 'collections.abc' is deprecated, and in 3.8 it will stop workin
#g
#  from collections import Iterable
#True
#True
#True
#True
#False
#calc.py:1115: DeprecationWarning: Using or importing the ABCs from 'collections'
# instead of from 'collections.abc' is deprecated, and in 3.8 it will stop workin
#g
#  from collections import Iterator
#True
#False
#False
#False
#<list_iterator object at 0x008C28B0> <class 'collections.abc.Iterator'>
#<dict_keyiterator object at 0x01058300> <class 'collections.abc.Iterator'>
#<str_iterator object at 0x008C2890> <class 'collections.abc.Iterator'>
#<generator object <genexpr> at 0x01051AB0> <class 'collections.abc.Iterator'>
#-------------------------

#print(abs(-10))
#print(abs)
#x=abs(-5)
#print(x)
#f=abs
#print(f)
#f=abs
#print(f(-10))
#def add(x,y,f):
#    return f(x)+f(y)
#print(add(-5,6,abs))
##输出结果
#10
#<built-in function abs>
#5
#<built-in function abs>
#10
#11
#-------------------------
#def f(x):
#    return x*x
#r=map(f,[1,2,3,4,5,6,7,8,9])
#print(r)
#print(list(r))
#L=[]
#for n in[1,2,3,4,5,6,7,8,9]:
#    L.append(f(n))
#print(L)
#x=list(map(str,[1,2,3,4,5,6,7,8,9]))
#print(x)
##reduce(f,[x1,x2,x3,x4])=f(f(f(x1,x2),x3),x4)
#from functools import reduce
#def add(x,y):
#    return x+y
#x=reduce(add,[1,3,5,7,9])
#print(x)
#def fn(x,y):
#    return x*10+y
#x=reduce(fn,[1,3,5,7,9])
#print(x)
#from functools import reduce
#def fn(x,y):
#    return x*10+y
#def char2num(s):
#    digits={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
#    return digits[s]
#x=reduce(fn,map(char2num,'13579'))
#print(x)
#from functools import reduce
#DIGITS={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
#def str2int(s):
#    def fn(x,y):
#        return x*10+y
#    def char2num(s):
#        return DIGITS[s]
#    return reduce(fn,map(char2num,s))
#print(str2int('16888'))
#def char2num(s):
#    return DIGITS[s]
#def str2int(s):
#    return reduce(lambda x,y:x*10+y,map(char2num,s))
#print(str2int('888168'))
#def myCapitalizeStr(s):
#    return s[0].upper()+s[1:].lower()
#x=map(myCapitalizeStr,['adam', 'LISA', 'barT'])
#print(list(x))
#def myProd(L):
#    def multiplicationStr(x,y):
#        return x*y
#    return reduce(multiplicationStr,L)
#print(myProd([1,2,3,4,5]))
#from functools import reduce
#def str2float(s):
#    def fn(x,y):
#        return x*10+y
#    def char2num(s):
#        return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
#    return reduce(fn,map(char2num,s.replace('.','')))
#myStr='123.456'
###有个报错TypeError: unsupported operand type(s) for *: 'dict' and 'int'
#if myStr.find('.')!=-1:
###    print('str2float(\'%s\') ='%myStr, str2float(myStr)/pow(10,(len(myStr)-myStr.find(".")-1))) 
#else:
#    print('str2float(\'%s\') ='%myStr,str2float(myStr))
#from functools import reduce
#def str2float(s):
#    def fn(x,y):
#        return x*10+y
#    n=s.index('.')
#    s1=list(map(int,[x for x in s[:n]]))
#    s2=list(map(int,[x for x in s[n+1:]]))
#    return reduce(fn,s1) + reduce(fn,s2)/10**len(s2)
#print('\'123.4567\'=',str2float('123.4567'))    
##输出结果
#<map object at 0x00942EB0>
#[1, 4, 9, 16, 25, 36, 49, 64, 81]
#[1, 4, 9, 16, 25, 36, 49, 64, 81]
#['1', '2', '3', '4', '5', '6', '7', '8', '9']
#25
#13579
#13579
#16888
#888168
#['Adam', 'Lisa', 'Bart']
#'123.4567'= 123.4567
#-------------------------
#def is_odd(n):
#    return n%2==1
#x=list(filter(is_odd,[1,2,4,5,6,9,10,15]))
#print(x)
#def not_empty(s):
#    return s and s.strip()
#x=list(filter(not_empty,['A','','B',None,'C',' ']))
#print(x)
###质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数
#def _odd_iter():
#    n=1
#    while True:
#        n=n+2
#        yield n
#def _not_divisible(n):
#    return lambda x:x%n>0
#def primes():
#    yield 2
#    it=_odd_iter()#初始序列
#    while True:
#        n=next(it)#返回序列的第一个数
#        yield n
#        it=filter(_not_divisible(n),it)#构造新队列
#for n in primes():
#    if n<20:
#        print(n)
#    else:
#        break
#def is_palindrome(n):
#    s = str(n)
#    for i in range(len(s)//2+1):
#        if s[i] != s[-1-i]:
#            return False
#    return True
#x=is_palindrome(12321)
#print(x)
####python中取整数的几种方法
#a=5//3
#print(a)
#a=-5//3
#print(a)
#a=5//-3
#print(a)
#a=-5//-3
#print(a)
#a=5%3
#print(a)
#a=5%-3
#print(a)
#a=-5%3
#print(a)
#a=-5%-3
#print(a)
#a=int(5.3)
#print(a)
#a=int(5.6)
#print(a)
#a=round(5.4)
#print(a)
#a=round(5.5)
#print(a)
#import math
#a=math.ceil(3.33)
#print(a)
#a=math.ceil(3.88)
#print(a)
#a=math.modf(4.25)
#print(a)
#a=math.modf(4.33)
#print(a)
###输出结果
#[1, 5, 9, 15]
#['A', 'B', 'C']
#2
#3
#5
#7
#11
#13
#17
#19
#True
#1
#-2
#-2
#1
#2
#-1
#1
#-2
#5
#5
#5
#6
#4
#4
#(0.25, 4.0)
#(0.33000000000000007, 4.0)
#-------------------------
#a=sorted([36,5,-12,9,-21])
#print(a)
#a=sorted([36,5,-12,9,-21],key=abs)
#print(a)
#a=sorted(['bob', 'about', 'Zoo', 'Credit'])
#print(a)
#a=sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower)
#print(a)
#a=sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True)
#print(a)
#L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
#def by_name(t):
#    return t[0].lower()
#def by_scort(t):
#    return t[1]
#print(sorted(L,key=by_name))
#print(L)
#print(sorted(L,key=by_scort,reverse=True))
#print(L)
###输出结果
#[-21, -12, 5, 9, 36]
#[5, 9, -12, -21, 36]
#['Credit', 'Zoo', 'about', 'bob']
#['about', 'bob', 'Credit', 'Zoo']
#['Zoo', 'Credit', 'bob', 'about']
#[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
#[('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
#[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
#[('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
#-------------------------
#def calc_sum(*args):
#    ax=0
#    for n in args:
#        ax=ax+n
#    return ax
#def lazy_sum(*args):
#    def sum():
#        ax=0
#        for n in args:
#            ax=ax+n
#        return ax
#    return sum
#f=lazy_sum(1,3,5,7,9)
#print(f)
#print(f())
#f1=lazy_sum(1,3,5,7,9)
#f2=lazy_sum(1,3,5,7,9)
#print(f1==f2)
#def count():
#    fs=[]
#    for i in range(1,4):
#        def f():
#            return i*i
#        fs.append(f)#闭包
#    return fs
#f1,f2,f3=count()
#print(f1())
#print(f2())
#print(f3())
#def count():
#    def f(j):
#        def g():
#            return j*j
#        return g
#    fs=[]
#    for i in range(1,4):
#        fs.append(f(i))# f(i)立刻被执行,因此i的当前值被传入f()
#    return fs
#f1,f2,f3=count()
#print(f1())
#print(f2())
#print(f3())
####利用闭包返回一个计数器函数,每次调用它返回递增整数:
#def createCounter():
#    s=[0]
#    def counter():
#        s[0]=s[0]+1
#        return s[0]
#    return counter
#print('AAAAA',createCounter()())
#print('AAAAA',createCounter()())
#s=3
#def createCounter2():
#    def counter():
#        global s 
#        s=s+1
#        return s
#    return counter
#counterA=createCounter2()
#print('BBBBB',counterA())
#print('BBBBB',counterA())
#def createCounter3():
#    def f():
#        x=0
#        while True:
#            x=x+1
#            yield x
#    sum=f()
#    def counter():
#        return next(sum)
#    return counter
#counterB=createCounter3()
#print('CCCCC',counterB())
#print('CCCCC',counterB())
###输出结果
#<function lazy_sum.<locals>.sum at 0x023B3FA8>
#25
#False
#9
#9
#9
#1
#4
#9
#AAAAA 1
#AAAAA 1
#BBBBB 4
#BBBBB 5
#CCCCC 1
#CCCCC 2
#-------------------------
#x=list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,9]))
#print(x)
#f=lambda x:x*x
#print(f)
#print(f(5))
#def build(x,y):
#    return lambda:x*x+y*y
#print(build(2,3)())
#def is_odd(n):
#    return n%2==1
#L=list(filter(is_odd,range(1,20)))
#print(L)
#M=list(filter(lambda n:n%2==1,range(1,20)))
#print(M)
###输出结果
#[1, 4, 9, 16, 25, 36, 49, 64, 81]
#<function <lambda> at 0x00B1FA08>
#25
#13
#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
#-------------------------
#def now():
#    print('2018-12-25')
#f=now
#print("AAA",f())
#g=now
#g()
#print(now.__name__)
#print(f.__name__)
#def log(func):
#    def wrapper(*args,**kw):
#        print('call %s():' % func.__name__)
#        return func(*args,**kw)
#    return wrapper
#@log
#def now():
#    print("2018-12-26")
#now()
####now=log(now)
#def log(text):
#    def decorator(func):
#        def wrapper(*args,**kw):
#            print('%s %s():' % (text,func.__name__))
#            return func(*args,**kw)
#        return wrapper
#    return decorator
#@log('execute')
#def now():
#    print('2018-12-26AAA')
#now()
#print(now.__name__)
#import functools
#def log(func):
#    @functools.wraps(func)
#    def wrapper(*args,**kw):
#        print('ABC_call %s():' % func.__name__)
#        return func(*args,**kw)
#    return wrapper
#@log
#def now():
#    print("2018-12-26cccc")
#now()
#import functools
#def log(text):
#    def decorator(func):
#        @functools.wraps(func)
#        def wrapper(*args,**kw):
#            print('%s %s():' % (text,func.__name__))
#            return func(*args,**kw)
#        return wrapper
#    return decorator
#@log('execute')
#def now():
#    print("2018-12-26DDDDD")
#now()
###请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
#import functools,time
#def log(text):
#    def decorator(func):
#        @functools.wraps(func)
#        def wrapper(*args,**kw):
#            if text!=None:
#                start=time.time()
#                res=func(*args,**kw)
#                end=time.time()
#                print('The text is %s and the call %s() runned in %s ms:'%(text,func.__name__,(end-start)*1000))
#                return res
#            else:
#                print('call %s():'%func.__name__)
#                start=time.time()
#                res=func(*args,**kw)
#                end=time.time()
#                print('call %s() runned in %s ms:'%(func.__name__,(end-start)*1000))
#                return res
#        return wrapper
#    if isinstance(text,str):#首先如果有参数 就跟原来一样直接返回decorator即可
#        return decorator
#    else:#如果没有参数 其实log(func)就是log里边其实直接传的参数就是func 返回的应该是wrapper 
#        func=text
#        text=None
#        return decorator(func)#所以这里的应该是直接decorator(func) 返回wrapper
#@log('there is a parameter in this edition')
#def f1(x,y):
#    time.sleep(2)#作用是让函数暂停2s在执行,就是计算函数执行的时间的
#    return x*y
#def main1():
#    result=f1(2,3)
#    print('the result is {}'.format(result))
#    print('the name of this function(no_parameter) is '+f1.__name__)
#@log
#def f2(x,y):
#    time.sleep(2)#作用是让函数暂停2s在执行,就是计算函数执行的时间的
#    return x+y
#def main2():
#    result=f2(5,8)
#    print("the result of this function(with parameter) is {}".format(result))
#    print("the name of this function is "+f2.__name__)    
#def main():
#    number=eval(input('please input a number to decide which the function to run:'))
#    if number==1:
#        main1()
#        print('mian_1_run sucessfully')
#    else:
#        main2()
#        print('mian_2_run sucessfully')
#main()        
###输出结果
#2018-12-25
#AAA None
#2018-12-25
#now
#now
#call now():
#2018-12-26
#execute now():
#2018-12-26AAA
#wrapper
#ABC_call now():
#2018-12-26cccc
#execute now():
#2018-12-26DDDDD
#please input a number to decide which the function to run:1
#The text is there is a parameter in this edition and the call f1() runned in 200
#0.0 ms:
#the result is 6
#the name of this function(no_parameter) is f1
#mian_1_run sucessfully
#please input a number to decide which the function to run:2
#call f2():
#call f2() runned in 2000.0 ms:
#the result of this function(with parameter) is 13
#the name of this function is f2
#mian_2_run sucessfully
#-------------------------
#x = 5
#y = x.bit_length()
#print(y)
#print(int('12345'))
#print(int('12345',base=8))
#print(int('12345',16))
#def int2(x,base=2):
#    return int(x,base)
#print(int2('1000000'))
#print(int2('1010101'))
#import functools
#int2=functools.partial(int,base=2)
#print('AAA',int2('1000000'))
#print('AAA',int2('1010101'))
#print('AAA',int2('1000000',base=10))
###输出结果
#3
#12345
#5349
#74565
#64
#85
#AAA 64
#AAA 85
#AAA 1000000
#-------------------------
##!/usr/bin/env python3
## -*- coding: utf-8 -*-
#'a test module'
#__author__='my name'
#
#import sys
#def test():
#    args=sys.argv 
#    #运行python3 hello.py获得的sys.argv就是['hello.py']
#    #运行python3 hello.py MyName获得的sys.argv就是['hello.py', 'MyName']。
#    if len(args)==1:
#        print('Hello,World!')
#    elif len(args)==2:
#        print('Hello,%s!'%args[1])
#    else:
#        print('Too many arguments!')
#if __name__=='__main__':
#    test()
#def _private_1(name):
#    return 'Hello,%s'%name
#def _private_2(name):
#    return 'Hi, %s'%name
#def greeting(name):
#    if len(name)>3:
#        return _private_1(name)
#    else:
#        return _private_2(name)
#print(greeting('ABCD'))
#print(greeting('AB'))
###输出结果
#Hello,World!
#Hello,ABCD
#Hi, AB
#-------------------------
#class Student(object):
#    pass
#bart=Student()
#print(bart)
#print(Student)
#bart.name='Bart Simpson'
#print(bart.name)
#class Student(object):
#    def __init__(self,name,score):
#        self.name=name
#        self.score=score
#    def print_score(self):
#        print('%s: %s'%(self.name,self.score))
#    def get_grade(self):
#        if self.score>=90:
#            return'A'
#        elif self.score>=60:
#            return'B'
#        else:
#            return'C'
#bart=Student('Bart Simpson',69)
#print('AAA',bart.name)
#print('AAA',bart.score)
#bart.print_score()
#lisa=Student('Lisa',99)
#bart=Student('Bart',59)
#print(lisa.name,lisa.get_grade())
#print(bart.name,bart.get_grade())
###输出结果
#<__main__.Student object at 0x02682E70>
#<class '__main__.Student'>
#Bart Simpson
#AAA Bart Simpson
#AAA 69
#Bart Simpson: 69
#Lisa A
#Bart C
#-------------------------
#class Student(object):
#    def __init__(self,name,score):
#        self.name=name
#        self.score=score
#bart=Student('Bart Simpson',69)
#print(bart.score)
#bart.score=99
#print(bart.score)
#class Student(object):
#    def __init__(self,name,score):
#        self.__name=name
#        self.__score=score
#    def print_score(self):
#        print('%s: %s'%(self.__name,self.__score))
#    def get_name(self):
#        return self.__name
#    def get_score(self):
#        return self.__score
#    def set_score(self,score):
#        if 0<=score<=100:
#            self.__score=score
#        else:
#            raise ValueError('Bad Score!')
#bart=Student('Bart Simpson AA',69)
###print(bart.__name) # 这个会报错 AttributeError: 'Student' object has no attribute '__name'
#print(bart.get_name())
#bart.__name='NewName'
#print(bart.__name)
#print('ABCDE',bart.get_name())
###请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性:
#class Student(object):
#    def __init__(self,name,gender):
#        self.__name=name
#        self.__gender=gender
#    def set_gender(self,gender):
#        self.__gender=gender
#    def get_gender(self):
#        return self.__gender
#bart=Student('Bart','male')
#if bart.get_gender()!='male':
#    print('male测试失败!')
#else:
#    bart.set_gender('female')
#    if bart.get_gender()!='female':
#        print('female测试失败!')
#    else:
#        print('female测试成功!')
###输出结果
#69
#99
#Bart Simpson AA
#NewName
#ABCDE Bart Simpson AA
#female测试成功!
#-------------------------
#class Animal(object):
#    def run(self):
#        print('Animal is running...')
#class Dog(Animal):
#    pass
#class Cat(Animal):
#    pass
#dog=Dog()
#dog.run()
#cat=Cat()
#cat.run()
#class Dog(Animal):
#    def run(self):
#        print('Dog is running...')
#class Cat(Animal):
#    def run(self):
#        print('Cat is running...')
#dog=Dog()
#dog.run()
#cat=Cat()
#cat.run()
#a=list()
#b=Animal()
#c=Dog()
#print(isinstance(a,list))
#print(isinstance(b,Animal))
#print(isinstance(c,Dog))
#print(isinstance(c,Animal))
#print(isinstance(b,Dog))
#def run_twice(animal):
#    animal.run()
#    animal.run()
#run_twice(Animal())
#run_twice(Dog())
#run_twice(Cat())
#class Tortoise(Animal):
#    def run(self):
#        print('Tortoise is running slowly...')
#run_twice(Tortoise())
###输出结果
#Animal is running...
#Animal is running...
#Dog is running...
#Cat is running...
#True
#True
#True
#True
#False
#Animal is running...
#Animal is running...
#Dog is running...
#Dog is running...
#Cat is running...
#Cat is running...
#Tortoise is running slowly...
#Tortoise is running slowly...
#-------------------------
#print(type(123))
#print(type('str'))
#print(type(None))
#class Animal(object):
#    def run(self):
#        print('Animal is running...')
#a=Animal()
#print(type(abs))
#print(type(a))
#print(type(123)==type(456))
#print(type(123)==int)
#print(type('abc')==type('456'))
#print(type('abc')==str)
#print(type('abc')==type(456))
#import types
#def fn():
#    pass
#print('A123A',type(fn)==types.FunctionType)
#print(type(abs)==types.BuiltinFunctionType)
#print(type(lambda x:x)==types.LambdaType)
#print(type((x for x in range(10)))==types.GeneratorType)
#print('A123B',isinstance('a',str))
#print(isinstance(123,int))
#print(isinstance(b'a',bytes))
#print(isinstance([1,2,3],(list,tuple)))
#print(isinstance((1,2,3),(list,tuple)))
#print(dir('ABC'))
#print(len('ABC'))
#print('ABCD'.__len__())
#class MyDog(object):
#    def __len__(self):
#        return 100
#dog=MyDog()
#print(len(dog))
#print('ABC'.lower())
#class MyObject(object):
#    def __init__(self):
#        self.x=9
#    def power(self):
#        return self.x*self.x
#obj=MyObject()
#print(hasattr(obj,'x'))
#print(obj.x)
#print(hasattr(obj,'y'))
#print(setattr(obj,'y',19))
#print(hasattr(obj,'y'))
#print(getattr(obj,'y'))
#print(obj.y)
###print(getattr(obj,'z')) #这个会报错 AttributeError: 'MyObject' object has no attribute 'z'
#print(getattr(obj,'z',404))
#print(hasattr(obj,'power'))
#print(getattr(obj,'power'))
#fn=getattr(obj,'power')
#print(fn)
#print(fn())
###输出结果
#<class 'int'>
#<class 'str'>
#<class 'NoneType'>
#<class 'builtin_function_or_method'>
#<class '__main__.Animal'>
#True
#True
#True
#True
#False
#A123A True
#True
#True
#True
#A123B True
#True
#True
#True
#True
#['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '_
#_eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs
#__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__'
#, '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
#'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__'
#, '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'e
#ncode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isal
#num', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', '
#isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lo
#wer', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
# 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
# 'swapcase', 'title', 'translate', 'upper', 'zfill']
#3
#4
#100
#abc
#True
#9
#False
#None
#True
#19
#19
#404
#True
#<bound method MyObject.power of <__main__.MyObject object at 0x008FF2D0>>
#<bound method MyObject.power of <__main__.MyObject object at 0x008FF2D0>>
#81
#-------------------------

#class Student(object):
#    def __init__(self,name):
#        self.name=name
#s=Student('Bob')
#s.score=90
#print(s.name)
#print(s.score)
#class Student(object):
#    name='StudentA'
#s=Student()
#print(s.name)
#s.name='XIZONG'
#print(s.name)
#print(Student.name)
#del s.name
#print(s.name)
#class Student(object):
#    count=0
#    def __init__(self,name):
#        self.name=name
#        Student.count+=1
#    def get_count(self):
#        return self.count
#bart=Student('Bart')
#print("AA",Student.count,'BB',bart.get_count())
#lisa=Student('Lisa')
#print("CC",Student.count,'DD',bart.get_count())
###输出结果
#Bob
#90
#StudentA
#XIZONG
#StudentA
#StudentA
#AA 1 BB 1
#CC 2 DD 2
#-------------------------
#class Student(object):
#    pass
#s=Student()
#s.name='Jack'
#print(s.name)
#def set_age(self,age):
#    self.age=age
#from types import MethodType
#s.set_age=MethodType(set_age,s)
#s.set_age(25)
#print(s.age)
#s2=Student()
###s2.set_age(26) #这个会报错 AttributeError: 'Student' object has no attribute 'set_age'
#def set_score(self,score):
#    self.score=score
#Student.set_score=set_score
#s.set_score(100)
#print(s.score)
#s2.set_score(99)
#print(s2.score)
#class Student(object):
#    __slots__=('name','age')
#s=Student()
#s.name='Steven'
#s.age=20
###s.score=99 #这个会报错 AttributeError: 'Student' object has no attribute 'score'
#class GraduateStudent(Student):
#    pass
#g=GraduateStudent()
#g.score=98
###输出结果
#Jack
#25
#100
#99
#-------------------------
#class Student(object):
#    def get_score(self):
#        return self._score
#    def set_score(self,value):
#        if not isinstance(value,int):
#            raise ValueError('score must be an integer!')
#        if value<0 or value>100:
#            raise ValueError('score must between 0~100!')
#        self._score=value
#s=Student()
#s.set_score(60)
#print(s.get_score())
###s.set_score(9999) #这个会报错 ValueError: score must between 0~100!
#class Student(object):
#    @property
#    def score(self):
#        return self._score
#    @score.setter
#    def score(self,value):
#        if not isinstance(value,int):
#            raise ValueError('score must be an integer!')
#        if value<0 or value>100:
#            raise ValueError('score must between 0~100!')
#        self._score=value
#    @property
#    def birth(self):
#        return self._birth
#    @birth.setter
#    def birth(self,value):
#        self._birth=value
#    @property
#    def age(self):
#        return 2018-self._birth  
#s=Student()
#s.score=61
#print(s.score)
###s.score=9999 #这个会报错 ValueError: score must between 0~100!
#s.birth=2000
#print(s.birth)
#print(s.age)
###s.age=20 #这个会报错 AttributeError: can't set attribute
#class Screen(object):
#    @property
#    def width(self):
#        return self._width
#    @width.setter
#    def width(self,value):
#        if not isinstance(value,int):
#            raise ValueError('width must be an integer!')
#        if value<0:
#            raise ValueError('width must over zero!')
#        self._width=value
#    @property
#    def height(self):
#        return self._height
#    @height.setter
#    def height(self,value):
#        if not isinstance(value,int):
#            raise ValueError('height must be an integer!')
#        if value<0:
#            raise ValueError('height must over zero!')
#        self._height=value
#    @property
#    def resolution(self):
#        return self._width*self._height
#s=Screen()
#s.width=1024
#s.height=768
#print(s.resolution)        
###输出结果
#60
#61
#2000
#18
#786432
#-------------------------
#class Student(object):
#    def __init__(self,name):
#        self.name=name
#print(Student('Jack'))
#class Student(object):
#    def __init__(self,name):
#        self.name=name
#    def __str__(self):
#        return 'Student object (name: %s)' %self.name
#    __repr__=__str__
#print(Student('JackA'))
#s=Student('JackB')
#s #直接敲变量,好像么有输出啊
#class Fib(object):
#    def __init__(self):
#       self.a,self.b=0,1
#    def __iter__(self):
#        return self
#    def __next__(self):
#        self.a,self.b=self.b,self.a+self.b
#        if self.a>20:
#            raise StopIteration()
#        return self.a
#    def __getitem__(self,n):
#        if isinstance(n,int):
#            a,b=1,1
#            for x in range(n):
#                a,b=b,a+b
#            return a
#        if isinstance(n,slice):
#            start=n.start
#            stop=n.stop
#            if start is None:
#                start=0
#            a,b=1,1
#            L=[]
#            for x in range(stop):
#                if x>=start:
#                    L.append(a)
#                a,b=b,a+b
#            return L
#for n in Fib():
#    print(n)
#f=Fib()
#print('ABC',f[4])
#print(f[0:3])
#class Student(object):
#    def __init__(self):
#        self.name='Jack'
#    def __getattr__(self,attr):
#        if attr=='score':
#            return 99
#        if attr=='age':
#            return lambda:25
#s=Student()
#print(s.name)
#print(s.score)
#print(s.age)
#print(s.age())
#class Student(object):
#    def __init__(self,name):
#        self.name=name
#    def __call__(self):
#        print('My name is %s'%self.name)
#s=Student('Jack')
#s()
#print(callable(Student('')))
#print(callable(max))
#print(callable([1,2,3]))
#print(callable(None))
#print(callable('str'))
###输出结果
#<__main__.Student object at 0x00F12F50>
#Student object (name: JackA)
#1
#1
#2
#3
#5
#8
#13
#ABC 5
#[1, 1, 2]
#Jack
#99
#<function Student.__getattr__.<locals>.<lambda> at 0x00B00A08>
#25
#My name is Jack
#True
#True
#False
#False
#False
#-------------------------
#from enum import Enum
#Month=Enum('MonthAB',('Jan','Feb','Mar','Apr'))
#for name,member in Month.__members__.items():
#    print(name,'=>',member,',',member.value)
#from enum import Enum,unique
#@unique
#class Weekday(Enum):
#    Sun=0
#    Mon=1
#    Tue=2
#    Wed=3
#day1=Weekday.Mon
#print(day1)
#print(Weekday.Tue)
#print(Weekday['Tue'])
#print(Weekday.Tue.value)
#print(day1==Weekday.Mon)
#print(day1==Weekday.Tue)
#print(Weekday(1))
#print(Weekday(1)==day1)
###Weekday(7) #这个会报错 ValueError: 7 is not a valid Weekday
#class Gender(Enum):
#    Male=0
#    Female=1
#class Student(object):
#    def __init__(self,name,gender):
#        self.name=name
#        self.gender=gender
#bart=Student('Bart',Gender.Male)
#if bart.gender==Gender.Male:
#    print('AAAAAAAAAAAAAA')
#else:
#    print('BBBBBBBBBBBBBB')
###输出结果
#Jan => MonthAB.Jan , 1
#Feb => MonthAB.Feb , 2
#Mar => MonthAB.Mar , 3
#Apr => MonthAB.Apr , 4
#Weekday.Mon
#Weekday.Tue
#Weekday.Tue
#2
#True
#False
#Weekday.Mon
#True
#AAAAAAAAAAAAAA
#-------------------------
#class Hello(object):
#    def hello(self,name='world'):
#        print('Hello,%s'%name)
###from hello import Hello  #这个会报错  这个不跨文件有错误 ModuleNotFoundError: No module named 'hello'
#h=Hello()
#h.hello()
#print(type(Hello))
#print(type(h))
#def fn(self,name='world'):
#    print('AAHello,%s'%name)
#HelloB=type('HelloA',(object,),dict(helloA=fn))
#h=HelloB()
#h.helloA()
#print(type(HelloB))
#print(type(h))
#class ListMetaclass(type):
#    def __new__(cls,name,bases,attrs):
#        attrs['add']=lambda self,value:self.append(value)
#        return type.__new__(cls,name,bases,attrs)
#class MyList(list,metaclass=ListMetaclass):
#    pass
#L=MyList()
#L.add(1)
#print(L)
#L2=list()
###L2.add(2) #这个会报错 AttributeError: 'list' object has no attribute 'add'
#class Field(object):
#    def __init__(self,name,column_type):
#        self.name=name
#        self.column_type=column_type
#    def __str__(self):
#        return '<%s:%s>'%(self.__class__.__name__,self.name)
#class StringField(Field):
#    def __init__(self,name):
#        super(StringField,self).__init__(name,'varchar(100)')
#class IntegerField(Field):
#    def __init__(self,name):
#        super(IntegerField,self).__init__(name,'bigint')
#class ModelMetaclass(type):
#    def __new__(cls,name,bases,attrs):
#        if name=='Model':
#            type.__new__(cls,name,bases,attrs)
#        print('Found model: %s'%name)
#        mappings=dict()
#        for k,v in attrs.items():
#            if isinstance(v,Field):
#                print('Found mapping: %s ==> %s'%(k,v))
#                mappings[k]=v
#        for k in mappings.keys():
#            attrs.pop(k)
#        attrs['__mappings__']=mappings
#        attrs['__table__']=name
#        return type.__new__(cls,name,bases,attrs)
#class Model(dict,metaclass=ModelMetaclass):
#    def __init__(self,**kw):
#        super(Model,self).__init__(**kw)
#    def __getattr__(self,key):
#        try:
#            return self[key]
#        except KeyError:
#            raise AttributeError(r"'Model'object has no attribute '%s'"%key)
#    def __setattr__(self,key,value):
#        self[key]=value
#    def save(self):
#        fields=[]
#        params=[]
#        args=[]
#        for k,v in self.__mappings__.items():
#            fields.append(v.name)
#            params.append('?')
#            args.append(getattr(self,k,None))
#        sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
#        print('SQL: %s'%sql)
#        print('ARGS: %s'%str(args))
#class User(Model):
#    id = IntegerField('id')
#    name = StringField('username')
#    email = StringField('email')
#    password = StringField('password')
#u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
#u.save()
###输出结果
#Hello,world
#<class 'type'>
#<class '__main__.Hello'>
#AAHello,world
#<class 'type'>
#<class '__main__.HelloA'>
#[1]
#Found model: Model
#Found model: User
#Found mapping: id ==> <IntegerField:id>
#Found mapping: name ==> <StringField:username>
#Found mapping: email ==> <StringField:email>
#Found mapping: password ==> <StringField:password>
#SQL: insert into User (id,username,email,password) values (?,?,?,?)
#ARGS: [12345, 'Michael', 'test@orm.org', 'my-pwd']
#-------------------------
#def foo(s):
#    n=int(s)
#    print('AAAn=%d'%n)
#    assert n!=0,'n is zero!'
#    return 10/n
#def main():
#    foo('0')
###main()
#import logging,pdb
#logging.basicConfig(level=logging.INFO)
#s='0'
#n=int(s)
#pdb.set_trace()
#logging.info('n=%d'%n)
#print(10/n)
#-------------------------
#from io import StringIO
#f=StringIO()
#f.write('hello')
#f.write(' ')
#f.write('world')
#print(f.getvalue())
#f=StringIO('Hello!\nhi\nGoodBye')
#while True:
#    s=f.readline()
#    if s=='':
#        break
#    print(s.strip())
#from io import BytesIO
#f=BytesIO()
#f.write('中文'.encode('utf-8'))
#print(f.getvalue())
#f=BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
#print(f.read())
###输出结果
#hello world
#Hello!
#hi
#GoodBye
#b'\xe4\xb8\xad\xe6\x96\x87'
#b'\xe4\xb8\xad\xe6\x96\x87'
#-------------------------
#import os 
#print(os.name)
###print(os.uname())
##print(os.environ)
##print(os.environ.get('PATH'))
#print(os.path.abspath('.'))
#print(os.path.join('D:\Learn_Python_Folder','testDir'))
###os.mkdir(b'D:\Learn_Python_Folder\testDir')
#def mkdir(path):
#    path=path.strip()# 去除首位空格
#    path=path.rstrip("\\")# 去除尾部 \ 符号
#    isExists=os.path.exists(path)
#    if not isExists:
#        os.makedirs(path) 
#        print(path,' 创建成功')
#        return True
#    else:
#        print(path,' 目录已存在')
#        return False
#mkpath="D:\\Learn_Python_Folder\\testDir"
#mkdir(mkpath)
#def rmdir(path):  
#    if os.path.exists(path):
#        os.rmdir(path)
#        print(path,' 删除成功')
#    else:
#        print('no such Folder:%s'%my_file)  # 则返回文件不存在
#rmdir("D:\\Learn_Python_Folder\\testDir")  
#import os,time
#currentdir = os.getcwd()
#print(currentdir)
#filenum, filesize, dirnum = 0, 0, 0
#for name in os.listdir(currentdir):
#    if os.path.isfile(name):
#        print('%s\t\t%d\t%s' % (time.strftime('%Y/%m/%d %H:%M', time.localtime(os.path.getmtime(name))), os.path.getsize(name), name))
#        filenum += 1
#        filesize += os.path.getsize(name)
#    elif os.path.isdir(name):
#        print('%s\t<DIR>\t\t%s' % (time.strftime('%Y/%m/%d %H:%M', time.localtime(os.path.getmtime(name))), name))
#        dirnum += 1
#print('\t\t%d个文件\t\t%d 字节' % (filenum, filesize))
#print('\t\t%d个目录' % dirnum)
#def search(dststr, path=['.']):
#    for n in path:
#        dirlist = [x for x in os.listdir(n) if os.path.isdir(os.path.join(n, x))]   
#        filelist = [x for x in os.listdir(n) if os.path.isfile(os.path.join(n, x)) and dststr in os.path.splitext(x)[0]]
#        if len(filelist) > 0:
#            print(n, ':')
#            for m in filelist:
#                print(m)
#            print('\n')
#        path = [os.path.join(n, x) for x in dirlist]
#        search(dststr, path)
#    return 'Done'
#dststr = 'MouseMove'
#search(dststr)
#import pickle
#d=dict(name='Bob',age=20,score=88)
#print(pickle.dumps(d))
#f=open('dump.txt','wb')
#pickle.dump(d,f)
#f.close() #输出:在统计目录创建一个txt,里边是bytes内容
#f=open('dump.txt','rb')
#d=pickle.load(f)
#f.close()
#print(d) #输出 {'name': 'Bob', 'age': 20, 'score': 88}
import json
#d=dict(name='Jack',age=20,score=88)
#json.dumps(d)
#json_str='{"age": 20, "score": 88, "name": "BobAA"}'
#print(json.loads(json_str))
#class Student(object):
#    def __init__(self,name,age,score):
#        self.name=name
#        self.age=age
#        self.score=score
#def student2dict(std):
#        return {
#        'name': std.name,
#        'age': std.age,
#        'score': std.score
#        }
#s=Student('Bob',20,88)
#print(json.dumps(s, default=student2dict))
#print(json.dumps(s,default=lambda obj:obj.__dict__))
##python json.dumps 中的ensure_ascii 参数引起的中文编码问题
#import json
#print(json.dumps('中国'))
#print(json.dumps('中国',ensure_ascii=False))
#-------------------------

#print('ABC\\-001')
#print(r'ABC\-001')
#import re
#x=re.match(r'^\d{3}\-\d{3,8}$','010-12345')
#print(x)
#test='用户输入的字符串'
#if re.match(r'正则表达式',test):
#    print('ok')
#else:
#    print('failed')
#print('a b   c'.split(' '))
#print(re.split(r'\s+','a b   c'))
#print(re.split(r'[\s+\,]+','a,,,b,c  ,d, e    f'))
#print(re.split(r'[\s\,\;]+','a,b;;; c  d'))
#x=re.match(r'^(\d{3})\-(\d{3,8})$','010-12345')
#print('AAA',x)
#print(x.group(0))
#print(x.group(1))
#print(x.group(2))
#t='19:05:30'
#m= re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t)
#print(m.groups())
#d='2-14'
#m=re.match(r'^(0[1-9]|1[0-2]|[0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[0-9])$',d)
#print(m.groups())
#print(re.match(r'^(\d+)(0*)$','102300').groups())
#print(re.match(r'^(\d+?)(0*)$','102300').groups())
#re_telephone=re.compile(r'^(\d{3})-(\d{3,8})$')
#print(re_telephone.match('010-12345').groups())
#print(re_telephone.match('010-8086').groups())
###写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email
#reg=r'^(<\w[\s\w]+>\s)?(\w+[\w+.]*@\w+.(org|com)$)'
#m=re.compile(reg)
#if m.match('someone@gmail.com'):
#    print('match someone@gmail.com')
#if m.match('bill.gates@microsoft.com'):
#    print('match bill.gates@microsoft.com')
#if m.match('<Tom Paris> tom@voyager.org'):
#    print('match <Tom Paris> tom@voyager.org')
###提取出带名字的Email地址
#email = (m.match('<Tom Paris> tom@voyager.org')).group(2)
#print(email)
###输出结果
#ABC\-001
#ABC\-001
#<re.Match object; span=(0, 9), match='010-12345'>
#failed
#['a', 'b', '', '', 'c']
#['a', 'b', 'c']
#['a', 'b', 'c', 'd', 'e', 'f']
#['a', 'b', 'c', 'd']
#AAA <re.Match object; span=(0, 9), match='010-12345'>
#010-12345
#010
#12345
#('19', '05', '30')
#('2', '14')
#('102300', '')
#('1023', '00')
#('010', '12345')
#('010', '8086')
#match someone@gmail.com
#match bill.gates@microsoft.com
#match <Tom Paris> tom@voyager.org
#tom@voyager.org    
#-------------------------
#from datetime import datetime
#now=datetime.now()
#print(now)
#print(type(now))
#dt=datetime(2019,1,14,15,54)
#print(dt)
#print(dt.timestamp())
#t=1547452440.0
#print(datetime.fromtimestamp(t))# 本地时间
#print(datetime.utcfromtimestamp(t))# UTC时间
#cday=datetime.strptime('2019-8-1 15:20:20','%Y-%m-%d %H:%M:%S')
#print(cday)
#now=datetime.now()
#print(now.strftime('%a,%b %d %H:%M'))
#now=datetime.now()
#print(now)
#from datetime import timedelta
#print(now+timedelta(hours=10))
#print(now-timedelta(days=1))
#print(now+timedelta(days=2,hours=12))
#from datetime import timezone
#tz_utc_8=timezone(timedelta(hours=8))
#now=datetime.now()
#print('AAA',now)
#dt=now.replace(tzinfo=tz_utc_8)
#print(dt)
#utc_dt=datetime.utcnow().replace(tzinfo=timezone.utc)
#print('UTC_DT',utc_dt)
#bj_dt=utc_dt.astimezone(timezone(timedelta(hours=8)))
#print(bj_dt)
#tokyo_dt=utc_dt.astimezone(timezone(timedelta(hours=9)))
#print(tokyo_dt)
#tokyo_dt2=bj_dt.astimezone(timezone(timedelta(hours=9)))
#print(tokyo_dt2)
###假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,
###均是str,请编写一个函数将其转换为timestamp
#from datetime import datetime,timezone,timedelta
#import re
#def toTimeStamp(str_time,str_utc):
#    td_time=datetime.strptime(str_time,'%Y-%m-%d %H:%M:%S')
#    td_utc=(re.match(r'^UTC([+|-]\d{1,2}):00$',str_utc)).group(1)
#    td=timezone(timedelta(hours=int(td_utc)))
#    dt=td_time.replace(tzinfo=td)
#    return dt.timestamp()
#print(toTimeStamp('2015-1-21 9:01:30','UTC+8:00'))
###输出结果
#2019-01-14 16:42:47.850076
#<class 'datetime.datetime'>
#2019-01-14 15:54:00
#1547452440.0
#2019-01-14 15:54:00
#2019-01-14 07:54:00
#2019-08-01 15:20:20
#Mon,Jan 14 16:42
#2019-01-14 16:42:47.858076
#2019-01-15 02:42:47.858076
#2019-01-13 16:42:47.858076
#2019-01-17 04:42:47.858076
#AAA 2019-01-14 16:42:47.859076
#2019-01-14 16:42:47.859076+08:00
#UTC_DT 2019-01-14 08:42:47.859076+00:00
#2019-01-14 16:42:47.859076+08:00
#2019-01-14 17:42:47.859076+09:00
#2019-01-14 17:42:47.859076+09:00
#1421802090.0
#-------------------------
#from collections import namedtuple
#Point=namedtuple('Point',['x','y'])
#p=Point(1,2)
#print(p.x)
#print(p.y)
#print(isinstance(p,Point))
#print(isinstance(p,tuple))
#from collections import deque
#q=deque(['a','b','c'])
#q.append('x')
#q.appendleft('y')
#print(q)
#from collections import defaultdict
#dd=defaultdict(lambda:'N/A')
#dd['key1']='abc'
#print(dd['key1'])
#print(dd['key2'])
#from collections import OrderedDict
#d=dict([('a',1),('b',2),('c',3)])
#print(d)
#od=OrderedDict([('a',1),('b',2),('c',3)])
#print(od)
#od=OrderedDict()
#od['z']=1
#od['y']=2
#od['x']=3
#print(list(od.keys()))
#class LastUpdatedOrderedDict(OrderedDict):
#    def __init__(self,capacity):
#        super(LastUpdatedOrderedDict,self).__init__()
#        self._capacity=capacity
#    def __setitem__(self,key,value):
#        containsKey=1 if key in self else 0
#        if len(self)-containsKey>=self._capacity:
#            last=self.popitem(last=False)
#            print('remove:',last)
#        if containsKey:
#            del self[key]
#            print('set:',(key,value))
#        else:
#            print('add:',(key,value))
#        OrderedDict.__setitem__(self,key,value)
#dic=LastUpdatedOrderedDict(2)
#dic['a']=1
#print('.......')
#dic['b']=2
#print('.......')
#dic['c']=3
#print('.......')
#dic['b']=6        
#from collections import ChainMap
#import os,argparse
#defaults={
#    'color':'red',
#    'user':'guest'
#}
#parser=argparse.ArgumentParser()
#parser.add_argument('-u','--user')
#parser.add_argument('-c','--color')
#namespace=parser.parse_args()
#command_line_args={k:v for k,v in vars(namespace).items() if v}
#combined=ChainMap(command_line_args,os.environ,defaults)
#print('color=%s'%combined['color'])
#print('user=%s'%combined['user'])
#from collections import Counter
#c=Counter()
#for ch in 'programming':
#    c[ch]=c[ch]+1
#print(c)
###输出结果
#1
#2
#True
#True
#deque(['y', 'a', 'b', 'c', 'x'])
#abc
#N/A
#{'a': 1, 'b': 2, 'c': 3}
#OrderedDict([('a', 1), ('b', 2), ('c', 3)])
#['z', 'y', 'x']
#add: ('a', 1)
#.......
#add: ('b', 2)
#.......
#remove: ('a', 1)
#add: ('c', 3)
#.......
#set: ('b', 6)
#color=red
#user=guest
#Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})
#-------------------------
#import base64
#print(base64.b64encode(b'binary\x00string'))
#print(base64.b64decode(b'YmluYXJ5AHN0cmluZw=='))
#print(base64.b64encode(b'i\xb7\x1d\xfb\xef\xff'))
#print(base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff'))
#print(base64.urlsafe_b64decode(b'abcd--__'))
###请写一个能处理去掉=的base64解码函数
#def safe_base64decode(s):
#    if len(s)%4!=0:
#        s=s+bytes('=',encoding='utf-8')*(4-len(s)%4)
#        print('1:%s'%s)
#    if not isinstance(s,bytes):
#        s=bytes(s,encoding='utf-8')
#        print('s:%s'%s)
#    base64_string=base64.b64decode(s)
#    print('base64:%s'%base64_string)
#    return base64_string
#assert b'abcd'==safe_base64decode(b'YWJjZA=='),safe_base64decode('YWJjZA==')
#print('.......')
#assert b'abcd'==safe_base64decode(b'YWJjZA'),safe_base64decode('YWJjZA')
#n=10240099
#b1=(n&0xff000000)>>24
#b2=(n&0xff0000)>>16
#b3=(n&0xff00)>>8
#b4=n&0xff
#bs=bytes([b1,b2,b3,b4])
#print(bs)
#import struct
#print(struct.pack('>I',10240099))
#print(struct.unpack('>IH',b'\xf0\xf0\xf0\xf0\x80\x80'))
#s = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00'
#print(struct.unpack('<ccIIIIIIHH', s))
#
#def bmp_info(data):
#    info = struct.unpack('<ccIIIIIIHH', data[:30])
#    # struct.unpack 如果不明白的可以在廖雪峰老师的python课程中仔细看看,通俗理解就是将二进制数据解析出来
#    if info[0] == b'B' and (info[1] == b'M' or info[1] == b'A'):
#        # 这里是做相应的判断,判断是否为位图
#        return {
#            'width': info[6],
#            'height': info[7],
#            'color': info[9]
#        }
## 测试
#bmp_data = base64.b64decode('Qk1oAgAAAAAAADYAAAAoAAAAHAAAAAoAAAABABAAAAAAADICAAASCwAAEgsAAAAAAAAAAAAA/3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9/AHwAfAB8AHwAfAB8AHwAfP9//3//fwB8AHwAfAB8/3//f/9/AHwAfAB8AHz/f/9//3//f/9//38AfAB8AHwAfAB8AHwAfAB8AHz/f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9//3//f/9/AHwAfP9//3//f/9//3//f/9//38AfAB8AHwAfAB8AHwAfP9//3//f/9/AHwAfP9//3//f/9//38AfAB8/3//f/9//3//f/9//3//fwB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9/AHz/f/9/AHwAfP9//38AfP9//3//f/9/AHwAfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfP9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfAB8AHz/fwB8AHwAfAB8AHwAfAB8AHz/f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//38AAA==')
#bi = bmp_info(bmp_data)
#assert bi['width'] == 28
#assert bi['height'] == 10
#assert bi['color'] == 16
#print('ok')
#import hashlib
#md5=hashlib.md5()
#md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
#print(md5.hexdigest())
#md5=hashlib.md5()
#md5.update('how to use md5 in '.encode('utf-8'))
#md5.update('python hashlib?'.encode('utf-8'))
#print(md5.hexdigest())
#sha1=hashlib.sha1()
#sha1.update('how to use sha1 in '.encode('utf-8'))
#sha1.update('python hashlib?'.encode('utf-8'))
#print(sha1.hexdigest())
###设计一个验证用户登录的函数,根据用户输入的口令是否正确,返回True或False
#def calc_md5(password):
#    md5=hashlib.md5()
#    md5.update(password.encode('utf-8'))
#    return md5.hexdigest()
#def login(user,password):
#    for k,v in db.items():
#        if k==user:
#            if calc_md5(password)==v:
#                return True
#            else:
#                return False
#db={
#    'michael': 'e10adc3949ba59abbe56e057f20f883e',
#    'bob': '878ef96e86145580c38c87f0410ad153',
#    'alice': '99b1c2188db85afee403b1536010c2c9'
#}
#assert login('michael', '123456')
#assert login('bob', 'abc999')
#assert login('alice', 'alice2008')
#assert not login('michael', '1234567')
#assert not login('bob', '123456')
#assert not login('alice', 'Alice2008')
#print('ok')
#import hmac, random
#def hmac_md5(key, s):
#    return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()
#class User(object):
#    def __init__(self, username, password):
#        self.username = username
#        self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)])
#        self.password = hmac_md5(self.key, password)
#db = {
#    'michael': User('michael', '123456'),
#    'bob': User('bob', 'abc999'),
#    'alice': User('alice', 'alice2008')
#}
#def login(username, password):
#    user = db[username]
#    return user.password == hmac_md5(user.key, password) 
#assert login('michael', '123456')
#assert login('bob', 'abc999')
#assert login('alice', 'alice2008')
#assert not login('michael', '1234567')
#assert not login('bob', '123456')
#assert not login('alice', 'Alice2008')
#print('ok')
###输出结果
#b'YmluYXJ5AHN0cmluZw=='
#b'binary\x00string'
#b'abcd++//'
#b'abcd--__'
#b'i\xb7\x1d\xfb\xef\xff'
#base64:b'abcd'
#.......
#1:b'YWJjZA=='
#base64:b'abcd'
#b'\x00\x9c@c'
#b'\x00\x9c@c'
#(4042322160, 32896)
#(b'B', b'M', 691256, 0, 54, 40, 640, 360, 1, 24)
#ok
#d26a53750bc40b38b65a520292f69306
#d26a53750bc40b38b65a520292f69306
#2c76b57293ce30acef38d98f6046927161b46a44
#ok
#ok
#-------------------------
##几个“无限”迭代器
#import itertools
##natuals = itertools.count(1)
##for n in natuals:
##    print(n)
##cs = itertools.cycle('ABC')
##for c in cs:
##    print(c)
##ns = itertools.repeat('A', 3)
##for n in ns:
##    print(n)
##natuals = itertools.count(1)
##ns = itertools.takewhile(lambda x: x <= 10, natuals)
##print(list(ns))
####组成一个更大的迭代器
##for c in itertools.chain('ABC', 'XYZ'):
##    print(c)
####相邻的重复元素挑出来放在一起
##for key, group in itertools.groupby('AAABBBCCAAA'):
##    print(key, list(group))
##for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
##    print(key, list(group))
###计算圆周率可以根据公式 利用Python提供的itertools模块,我们来计算这个序列的前N项和
#def pi(N):
#    n=itertools.count(1,2)
#    ns=itertools.takewhile(lambda x:x<=2*N,n)
#    num=list(ns)
#    sum=0
#    for n in num:
#        if n%4==1:
#            n=4/n
#        else:
#            n=-4/n
#        sum+=n
#    return sum
#print(pi(10))
#print('-------')
#assert 3.04 < pi(10) < 3.05
#print('ok')
###输出结果
#3.0418396189294032
#-------
#ok
#-------------------------
#class Query(object):
#    def __init__(self, name):
#        self.name = name
#
#    def __enter__(self):
#        print('Begin')
#        return self
#    def __exit__(self, exc_type, exc_value, traceback):
#        if exc_type:
#            print('Error')
#        else:
#            print('End')
#    def query(self):
#        print('Query info about %s...' % self.name)
#with Query('Bob') as q:
#    q.query()
#from contextlib import contextmanager
#class Query(object):
#
#    def __init__(self, name):
#        self.name = name
#
#    def query(self):
#        print('Query info about %s...' % self.name)
#@contextmanager
#def create_query(name):
#    print('Begin')
#    q = Query(name)
#    yield q
#    print('End')    
#with create_query('Bob2') as q:
#    q.query()
#@contextmanager
#def tag(name):
#    print("<%s>" % name)
#    yield
#    print("</%s>" % name)
#with tag("h1"):
#    print("hello")
#    print("world")
#from contextlib import closing
#from urllib.request import urlopen
#with closing(urlopen('https://www.python.org')) as page:
#    for line in page:
#        print(line)#
#from urllib import request
#with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
#    data = f.read()
#    print('Status:', f.status, f.reason)
#    for k, v in f.getheaders():
#        print('%s: %s' % (k, v))
#    print('Data:', data.decode('utf-8'))
#req = request.Request('http://www.douban.com/')
#req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
#with request.urlopen(req) as f:
#    print('Status:', f.status, f.reason)
#    for k, v in f.getheaders():
#        print('%s: %s' % (k, v))
#    print('Data:', f.read().decode('utf-8'))
#print('Login to weibo.cn...')
#email = input('Email: ')
#passwd = input('Password: ')
#login_data = parse.urlencode([
#    ('username', email),
#    ('password', passwd),
#    ('entry', 'mweibo'),
#    ('client_id', ''),
#    ('savestate', '1'),
#    ('ec', ''),
#    ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
#])
#req = request.Request('https://passport.weibo.cn/sso/login')
#req.add_header('Origin', 'https://passport.weibo.cn')
#req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
#req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
#with request.urlopen(req, data=login_data.encode('utf-8')) as f:
#    print('Status:', f.status, f.reason)
#    for k, v in f.getheaders():
#        print('%s: %s' % (k, v))
#    print('Data:', f.read().decode('utf-8'))    
#from urllib import request
#import json
#def fetch_data(url):
#    req = request.Request(url)  # 请求url(GET请求)
#    with request.urlopen(req) as f:     # 打开url请求(如同打开本地文件一样)
#        return json.loads(f.read().decode('utf-8'))  # 读数据 并编码同时利用json.loads将json格式数据转换为python对象
#URL = 'http://m.maoyan.com/ajax/movieOnInfoList?token='
#data = fetch_data(URL)
#print(data)
#assert data['stid']== '576591972453269000'
#print('ok')
#-------------------------

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值