我的Python学习之路(一)

系统 655 0

我的Python学习之路(一)

  • 跟着廖雪峰的Python教程学习
    • Task 1:输入和输出
    • Task 2:打印变量
    • Task 3:格式化输出
    • Task 4:按要求打印tuple元素
    • Task 5:if分支练习
    • Task 6:循环练习
    • Task 7:调用函数
    • Task 8:定义函数
    • Task 9:可变参数
    • Task 10:递归函数实现
    • Task 11:切片练习
    • Task 12:迭代练习
    • Task 13: 列表生成式练习
    • Task 14:生成器练习
    • Task 15:map/reduce
    • Task 16:Filter练习
    • Task 17:sorted练习
    • Task 18:返回函数
    • Task 19:匿名函数
    • Task 20:装饰器
    • Task 21:类和实例练习
    • Task 22: 访问限制练习
    • Task 23:实例属性和类属性
    • Task 24: @property练习
    • Task 25: 定制类练习
    • Task 26:枚举类练习
    • Task 27:练习metaclass[ORM框架] **重要的高级知识点
    • Task 28:错误处理练习
    • 明日练习:调试 练习

跟着廖雪峰的Python教程学习

date:2019-06-25
从今天开始,我开始跟着廖雪峰的Python教程 学习Python,并将习题放到这儿,以便时时复习。

Task 1:输入和输出

            
              #!/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))

            
          

Task 2:打印变量

            
              #!/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)

            
          

Task 3:格式化输出

            
              #!/usr/bin/env python3
# -*- coding: utf-8 -*-
s1 = 72
s2 = 85

r = (s2-s1)/s1
print('%.1f%%' % r)

            
          

Task 4:按要求打印tuple元素

            
              #!/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])

            
          

Task 5:if分支练习

            
              #!/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('严重肥胖')

            
          

Task 6:循环练习

            
              #!/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

            
          

Task 7:调用函数

            
              #!/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)


            
          

Task 8:定义函数

请定义一个函数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))


            
          

Task 9:可变参数

            
              #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def product(x, *y):
    pro = x
    for val in y:
       pro = pro*val
    return pro


            
          

Task 10:递归函数实现

由于之前汉诺塔的解决方案忘了,因此此函数未写出来

            
              #!/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))

            
          

Task 11:切片练习

            
              #!/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

            
          

Task 12:迭代练习

            
               #!/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)

            
          

Task 13: 列表生成式练习

            
               #!/usr/bin/env python3
 # -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]

            
          

Task 14:生成器练习

没有得到最简方式,找到的最简方式

            
               #!/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

Task 15:map/reduce

以下我认为是最简洁的函数,我自己由于对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)   


            
          

Task 16:Filter练习

            
              #!/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

Task 17:sorted练习

            
              #!/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)

            
          

Task 18:返回函数

注:此节学习到作用域声明,虽然闭包可以使用外层作用域变量,但是如果要修改外部变量的值,也是需要声明变量是外层作用域或者全局变量的,如果修改的变量是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

            
          

Task 19:匿名函数

            
              # -*- coding: utf-8 -*-
def is_odd(n):
    return n % 2 == 1

L = list(filter(lambda n:n%2==1, range(1, 20)))

            
          

Task 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

Task 21:类和实例练习

在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)


            
          

Task 22: 访问限制练习

            
              #!/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

            
          

Task 23:实例属性和类属性

            
              #!/usr/bin/env python3
# -*- coding: utf-8 -*-


class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count = Student.count + 1

            
          

Task 24: @property练习

            
              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

            
          

Task 25: 定制类练习

在本章中,由于在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 由于出差一周,之前一直没空学习 今天继续

Task 26:枚举类练习

            
              #!/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('测试失败!')

            
          

Task 27:练习metaclass[ORM框架] **重要的高级知识点

            
              #!/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='test@orm.org', password='my-pwd')
# 保存到数据库:
u.save()


            
          

date:2019-7-7

Task 28:错误处理练习

            
              #!/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()

            
          

明日练习:调试 练习

调试 练习


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请请扫描上面二维码支持博主1元、2元、5元等您想捐的金额吧,狠狠点击下面给点支持吧

发表我的评论
最新评论 总共0条评论