date:2019-06-25
从今天开始,我开始跟着廖雪峰的Python教程 学习Python,并将习题放到这儿,以便时时复习。
#!/usr/bin/env python3
# -*- codeing: utf-8 -*-
#bypython
print('1024*768=',1024*768)
print('1024*768=%10d'%(1024*768))
print('1024*768=%010d'%(1024*768))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n = 123
f = 456.789
s1 = 'Hello, world'
s2 = 'Hello, \'Adam\''
s3 = r'Hello, "Bart"'
s4 = r'''Hello,
Lisa!'''
print('n=%d f=%.3f'%(n,f))
print(s1)
print('%s'%s2)
print(s3)
print(s4)
print(n,f,s1,s2,s3,s4)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s1 = 72
s2 = 85
r = (s2-s1)/s1
print('%.1f%%' % r)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print('%s'%L[0][0])
# 打印Python:
print('%s'%L[1][1])
# 打印Lisa:
print('%s'%L[2][2])
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
height = 1.75
weight = 80.5
bmi = weight/height**2
if bmi < 18.5:
print('过轻')
elif bmi < 25:
print('正常')
elif bmi < 28:
print('过重')
elif bmi < 32:
print('肥胖')
else:
print('严重肥胖')
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print('Hello, %s!'%name)
i = 0
while i < len(L):
print('Hello, %s!'%L[i])
i = i+1
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
print('0x%04X'%n1)
print('0x%04X'%n2)
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程 ax2+bx+c=0ax^2+bx+c=0ax2+bx+c=0 的两个解。
提示:
一元二次方程的求根公式为:
x=−b±b2−4ac2ax=\frac{-b\pm\sqrt{b^2-4ac}}{2a}x=2a−b±b2−4ac
计算平方根可以调用math.sqrt()函数:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
if (b**2 - 4*a*c) < 0:
return None,None
return ( (-b+math.sqrt(b**2 - 4*a*c))/(2*a), (-b-math.sqrt(b**2 - 4*a*c))/(2*a))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def product(x, *y):
pro = x
for val in y:
pro = pro*val
return pro
由于之前汉诺塔的解决方案忘了,因此此函数未写出来
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1,a,c,b)
move(1,a,b,c)
move(n-1,b,a,c)
#print("move(%d, %s,%s,%s)"%(n,a,b,c))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def trim(s):
if len(s) == 0:
return ''
flg = False
if s[0] == ' ':
s = s[1:]
flg = True
if s[-1] == ' ':
s = s[:-1]
flg = True
if flg :
s = trim(s)
return s
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def findMinAndMax(L):
min = None
max = None
for val in L:
if min == None or val < min:
min = val
if max == None or val > max :
max = val
return (min, max)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
没有得到最简方式,找到的最简方式
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def triangles():
p = [1]
while True:
yield p
p =[1]+[p[x]+p[x+1] for x in range(len(p)-1)]+[1]
date:2019-6-26
以下我认为是最简洁的函数,我自己由于对Python不熟,没有想到用切片来做
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def normalize(name):
return name[0].upper() + name[1:].lower()
#return name.capitalize() //首字母大写函数
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def prod(L):
def prod2(x, y):
return x*y
return reduce(prod2, L)
#return reduce(lambda x,y:x*y, L)
#!/usr/bin/env python3
# -*- coding: utf-8 -*
from functools import reduce
def str2float(s):
#TODO:这里应该判定全是数值
index = s.find('.')
if index == -1:
return int(s)
fl = len(s[index+1:])
return int(s[:index])+int(s[index+1:])/(10**fl)
#!/usr/bin/env python3
# -*- coding: utf-8 -*
def is_palindrome(n):
s = str(n)
strlen = len(s)
flg = True
for i in range(0, strlen//2):
if s[i] != s[strlen - i-1]:
flg = False
break
return flg
date:2019-6-27
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_name)
print(L2)
L2 = sorted(L, key=by_score)
print(L2)
注:此节学习到作用域声明,虽然闭包可以使用外层作用域变量,但是如果要修改外部变量的值,也是需要声明变量是外层作用域或者全局变量的,如果修改的变量是list,则不用声明
可使用 nonlocal 或者 global 关键字,推荐使用 nonlocal.并且如果使用的是global,内部声明也需要使用global
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def createCounter():
i = 0
def counter():
nonlocal i
i += 1
return i
return counter
# -*- coding: utf-8 -*-
def is_odd(n):
return n % 2 == 1
L = list(filter(lambda n:n%2==1, range(1, 20)))
附加知识:时间库 获取当前时间 time.time() 单位秒 结果为浮点数
# -*- coding: utf-8 -*-
import time, functools
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
t1 = time.time()*1000
res = fn(*args, **kw)
t2 = time.time()*1000
print('%s executed in %s ms' % (fn.__name__, int(t2-t1)) )
return res
return wrapper
熟悉第三方工具 Anaconda+PyCharm
在PyCharm中,发现工具会严格检查编码规范,因此了解了以下编码规范
另外如果不加括号(如下),不会调用__init__函数
class Student(object):
count = 0
def __init__(self):
Student.count = Student.count + 1
self._name = ''
print(Student.count)
a = Student()
# 错误示范 这样没有调用_init__函数
a = Student
print(Student.count)
b = Student()
print(Student.count)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self, val):
self.__gender = val
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
count = 0
def __init__(self, name):
self.name = name
Student.count = Student.count + 1
class Screen(object):
def __init__(self):
self.__width = 0
self.__height = 0
@property
def width(self):
return self.__width
@width.setter
def width(self, val):
self.__width = val
@property
def height(self):
return self.__height
@height.setter
def height(self, val):
self.__height = val
@property
def resolution(self):
return self.__width*self.__height
在本章中,由于在PyCharm中运行网站实例出现了,在最后测试Fib for循环输出时遇到死在其中不能退出,经过调试发现不知道为什么,for循环没有处理StopIteration异常,自己处理异常成功测试完成
求助得到,竟然是因为 使用了return异常,而不是raise异常,个人使用的PyCharm的没有提示警告
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name):
self.__name = name
def __str__(self):
return 'Object:Student(name:%s)'%self.__name
__repr__ = __str__
# 测试 __str__
print(Student('Michael'))
# 分割
class Fib(object):
def __init__(self):
self.__a, self.__b = 0, 1 # 初始化两个计数器 a,b
def __iter__(self):
return self # 实例本身是迭代对象
def __next__(self):
self.__a, self.__b = self.__b, self.__a + self.__b
if self.__a > 100: # 设置退出循环的条件
raise StopIteration()
# return StopIteration()
return self.__a # 返回下一个值
def __getitem__(self, idx):
__a, __b = 1, 1
for x in range(idx):
__a, __b = __b, __a + __b
return __a
# 测试__iter__,__getitem__
for n in Fib():
if isinstance(n, StopIteration):
break
else:
print(n)
f = Fib()
print(f[0])
print(f[1])
print(f[2])
print(f[3])
print(f[4])
date:2019-7-6 由于出差一周,之前一直没空学习 今天继续
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May'
, 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'
, 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
from enum import unique
@unique
class Weekday(Enum):
Sun = 0 #除了默认值外也可以指定枚举为对应的值
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Mon
print(day1)
print(Weekday.Tue)
print(Weekday['Tue'])
print(Weekday.Tue.value)
print(day1 == Weekday.Mon.value)
print(day1 == Weekday.Tue.value)
print(Weekday(1))
print(day1 == Weekday(1))
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('测试通过!')
else:
print('测试失败!')
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Field(object):
def __init__(self, name, column_type):
self.name = name
self.column_type = column_type
def __str__(self):
return '<%s:%s>'%(self.name, self.column_type)
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':
return type.__new__(cls, name, bases, attrs)
print('Fount 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, **kv):
super(Model, self).__init__(**kv)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Model' Obejct 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) value (%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='[email protected]', password='my-pwd')
# 保存到数据库:
u.save()
date:2019-7-7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from functools import reduce
try:
print('try...')
r = 10/0
print('result:', r)
except ZeroDivisionError as e:
print('Except:', e)
finally:
print('finally...')
print('END')
try:
print('try...')
r = 10/int('a')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('Except:', e)
else:
print('no error')
finally:
print('finally...')
print('END')
try:
print('try...')
r = 10/int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('Except:', e)
else:
print('no error')
finally:
print('finally...')
print('END')
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
def str2num(s):
return int(s)
def calc(exp):
ss = exp.split('+')
ns = map(str2num, ss)
return reduce(lambda acc, x: acc + x, ns)
def lmain():
r = calc('100 + 200 + 345')
print('100 + 200 + 345 =', r)
r = calc('99 + 88 + 7.6')
print('99 + 88 + 7.6 =', r)
lmain()
调试 练习