第一天

条件判断练习测试

# 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
# 用if-elif判断并打印结果:def exp_if():height = 1.75weight = 80.5bmi = weight/(height*height)if bmi<18.5:print("you BMI is {}".format(bmi))elif bmi<=25:print("you BMI is {},正常".format(bmi))elif bmi<=28:print("you BMI is {},过重".format(bmi))elif bmi<=32:print("you BMI is {},肥胖".format(bmi))else:print("you BMI is \t{:.3f},严重肥胖".format(bmi))if __name__ == '__main__':exp_if()

利用列表或者元组实现循环

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 = sum + x
print(sum)##实现计算0+1+2++100
sum=0
for i in range(101):sum=sum+i
print(sum)

计算100以内所有奇数之和

#法一:
sum=0
for i in range(1,100,2):sum=sum+i
print (sum)#法二:
sum=0
i=1
while i<101 :sum=sum+ii=i+2
print(sum)

标准化输出格式打印练习

#请利用循环依次对list中的每个名字打印出Hello, xxx!:
L = ['Bart', 'Lisa', 'Adam']
len=len(L)
for i in range(len):print("Hello {}".format(L[i]))

利用.format{}实现标准化输出格式定义

print "{:.2f}".format(3.1415926) #3.14,保留小数点后两位
print "{:+.2f}".format(3.1415926) #+3.14 带符号保留小数点后两位
print "{:+.2f}".format(-10) #-10.00 带符号保留小数点后两位
print "{:+.0f}".format(-10.00) #-10  不带小数
print "{:0>2d}".format(1) #01 数字补零 (填充左边, 宽度为2)
print "{:x<2d}".format(1) #1x 数字补x (填充右边, 宽度为4)
print "{:x<4d}".format(10) #10xx 数字补x (填充右边, 宽度为4)
print "{:,}".format(1000000) #1,000,000 以逗号分隔的数字格式
print "{:.2%}".format(0.12) #12.00% 百分比格式
print "{:.2e}".format(1000000) #1.00e+06 指数记法
print "{:<10d}".format(10) #10 左对齐 (宽度为10)
print "{:>10d}".format(10) #        10 右对齐 (默认, 宽度为10)
print "{:^10d}".format(10) #    10 中间对齐 (宽度为10)

字典使用

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

判断是否在字典中

def test_dict():SC={"Anan":"90","Ping":"88","Ling":"83"}print(SC['Ping'])print(SC.get('Ping'))
if __name__ == '__main__':test_dict()

实现输入一个name 如果在列表中 输出得分 判断得分等级 如果没有输出该名字不在名单内

def scoretest(score):if score>90:achievement ='优秀'elif score>=80:achievement ='良好'elif score >60:achievement='及格'else:achievement='不及格'return achievement
if __name__ == '__main__':input_name=input("Please input you name:")dict_name_and_score={"Anan":"90","Ping":"88","Ling":"55"}if input_name in dict_name_and_score:print('{} score is {} belong to {}'.format(input_name,dict_name_and_score[input_name],scoretest(int(dict_name_and_score[input_name]))))else:print("{} is not in our Name list".format(input_name))

实现计算园面积s=πr*r

import math
import numpy
def Circular_Area(r):PI=3.14s=PI*numpy.square(r)return(s)
if __name__ == '__main__':input=input("R is :")print("The circular area with a radius of {} is:{:.2f}".format(input,Circular_Area(int(input))))

函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax2 + bx + c = 0

import numpy as np
def quadratic(a,b,c):x1=(-b+np.sqrt(b*b-4*a*c))/(2*a)x2=(-b-np.sqrt(b*b-4*a*c))/(2*a)return(x1,x2)
def main():quadratic(1,3,-4)print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))if quadratic(2, 3, 1) != (-0.5, -1.0):print('测试失败')elif quadratic(1, 3, -4) != (1.0, -4.0):print('测试失败')else:print('测试成功')
if __name__ == '__main__':main()

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756044276a15558a759ec43de8e30eb0ed169fb11000

第二天

切片

L=[]
n=1
while n<99:L.append(n)n=n+2
print(L)
#取list或者元组的前三个元素# def test_list():
#   L=[]
#   n=1
#   while n<=99:
#       L.append(n)
#       n=n+2
#   # print(L)
#   print(L[:3])
#   # return L
#   pass# def test_tuple():
#   T=('Anan','Ping','Ling','Zhen')
#   # return T
#   print(T[:3])
#   print(T[::2]) #开始 结束 步长# if __name__ == '__main__':
#   # test_list()
#   test_tuple()

列表生成式训练

L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[]
j=0
for i in range(len(L1)-1):if isinstance(L1[i],str):L2.append(L1[i].lower())j=j+1
if L2 == ['hello', 'world', 'apple']:print('测试通过!')
else:print('测试失败!')

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000

第三天

高阶函数

def add(x, y, f):return f(x) + f(y)print(add(-5, 6, abs))
def add(x,y,f):return f(x)+f(y)def min(x,y,h):return(h(x)-h(y))
def h(z):return abs(z)if __name__ == '__main__':x=-5y=6f=abs# print(add(h(3),h(2)))print(min(h(3),h(2),h))print(min(3,4,h))

map reduace的实现


>map()函数接收两个参数 一个是函数 一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为Iterator返回

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#function (1) 利用map计算一个列表中数的平方  (2)利用reduace函数把序列[1, 3, 5, 7, 9]变换成整数13579
from functools import reduce
def f(x):return x*xdef map_test():r=map(f,[1, 2, 3, 4, 5, 6, 7, 8, 9])print(list(r))print(list(map(str,[1,2,3,3,45,5,5,4])))def fn(x,y):return x*10+ydef reduace_test():print(reduce(fn,[1,2,5,6]))pass
if __name__ == '__main__':# map_test()reduace_test()

结合MapReduace实现将字符转化为数字进行运算

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#function 结合MapReduace实现将字符转化为数字进行运算
from functools import reduce
def fn(x,y):return x*10+ydef 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]print(reduce(fn,map(char2num,'1456')))

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。


# -*- coding: utf-8 -*-
def normalize(name):name.title()
# 测试:
##输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

利用prod()函数实现可以接受一个list并利用reduce()求积:

from functools import reduce
def prod(L):sumL=1for i in range(len(L)):sumL=sumL*L[i]return sumLprint('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:print('测试成功!')
else:print('测试失败!')
from functools import reducedef prod(x,y):return x*y
result = reduce(prod,[3,5,7,9])
print(result)

把字符串’123.456’转换成浮点数123.456

def str2float(s):return float(s)print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:print('测试成功!')
else:print('测试失败!')

利用filter()筛选出回数

def is_palindrome(n):return str(n)==str(n)[::-1]
# 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:print('测试成功!')
else:print('测试失败!')

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_score)
print(L2)

匿名函数

关键字lambda表示匿名函数,冒号前面的x表示函数参数。

L=list(filter(lambda n :n%2==1,range(1,20)))
print(L)
def is_odd(n):return n % 2 == 1L1 = list(filter(is_odd, range(1, 20)))
print(L1)def is_odd2(n):return lambda n:n%2==1
L2 = list(filter(is_odd2(0), range(1, 20)))
print(L2)

python内建函数:https://docs.python.org/3/library/functions.html

第四天

实现面相对象编程

# !/usr/bin/env python
# -*- coding: utf-8 -*-
'实现面相对象编程'
class Student(object):"""docstring for Student"""def __init__(self, name,score):self.name=nameself.score=scoredef print_score(self):return '%s,%s'%(self.name,self.score)def get_grade(self):if self.score>=90:return 'A'elif self.score>=80:return 'B'elif self.score>=60:return 'C'else:return 'D'
def main():anan=Student('Anan',88)anan.print_score()print(anan.name,anan.score,anan.get_grade())if __name__ == '__main__':main()
'定义私有变量(private)'
class Student(object):def __init__(self, name,score):self.__name=nameself.__score=scoredef print_score(self):return '%s,%s'%(self.__name,self.__score)def get_name(self):return self.__namedef get_score(self):return self.__score
def main():anan=Student('Anan',88)print(anan.get_name(),anan.get_score())
if __name__ == '__main__':main()
'访问限制训练'
class Student(object):def __init__(self, name, gender):self.name = nameself.__gender = genderdef get_gender(self):return self.__genderdef set_gender(self,gender):self.__gender=genderreturn self.__genderdef test():bart = Student('Bart', 'male')if bart.get_gender() != 'male':print('测试失败!')else:bart.set_gender('female')if bart.get_gender() != 'female':print('测试失败!')else:print('测试成功!')if __name__ == '__main__':test()

继承和多态

#!/usr/bin/env python3
# -*- coding: utf-8 -*-class Animal(object):def run(self):print('Animal is running...')class Dog(Animal):def run(self):print('Dog is running...')class Cat(Animal):def run(self):print('Cat is running...')def run_twice(animal):animal.run()animal.run()a = Animal()
d = Dog()
c = Cat()print('a is Animal?', isinstance(a, Animal))
print('a is Dog?', isinstance(a, Dog))
print('a is Cat?', isinstance(a, Cat))print('d is Animal?', isinstance(d, Animal))
print('d is Dog?', isinstance(d, Dog))
print('d is Cat?', isinstance(d, Cat))run_twice(c)

为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:

class Student(object):count = 0def __init__(self, name):self.name = nameStudent.count+=1# 测试:
if Student.count != 0:print('测试失败!')
else:bart = Student('Bart')if Student.count != 1:print('测试失败!')else:lisa = Student('Bart')if Student.count != 2:print('测试失败!')else:print('Students:', Student.count)print('测试通过!')

使用slots

使用slots可以限制实例的属性,只允许对类的实例添加slots定义的属性
slots不能限制继承类的实例属性。如果被继承的类也需要进行限定需要子类也添加slots的限定

使用@property

IO编程

python读取文件:

'方法一'
f=open('filename','r')
f.read()
f.close()'方法二'#-->推荐
with open('filename','r') as f:f.read()python写入文件:
'方法一'
f=open('filename','w')
f.write()
f.close()'方法二'#-->推荐
with open('filename','w') as f:f.write('输入你需要写入的内容')方法三:
file=r'filename'
with open(file,'w+') as f:f.write('输入你需要写入的内容')

输入输出参数详解:

‘r’:读\
‘w’:写\
‘a’:追加\
‘r+’ == r+w(可读可写,文件若不存在就报错(IOError))\
‘w+’ == w+r(可读可写,文件若不存在就创建)\
‘a+’ ==a+r(可追加可写,文件若不存在就创建)\
对应的,如果是二进制文件,就都加一个b:\
‘rb’  ‘wb’  ‘ab’  ‘rb+’  ‘wb+’  ‘ab+’

正则表达式

\d匹配一个数字\
\w匹配一个字母或数字\
*表示任意个字符(包括0个)\
+表示至少一个字符\
?表示0个或1个字符\
{n}表示n个字符\
{n,m}表示n-m个字符\
A|B可以匹配A或B\
^表示行的开头\
^\d表示必须以数字开头\
表示行的结束 \d 表 示 行 的 结 束 \d 表示行的结束\ \d表示必须以数字结束

案例:正则匹配邮箱

test='bill.gates@microsoft.com'
if re.match(r'^[0-9a-zA-Z_.]+@[a-z]+.com$', test):print('ok')
else:print('failed')

装饰器

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def aa(func):def bb():print("abc")result=func()return bb@aa
def main():print("main")if __name__ == '__main__':main()

未完待续…

廖雪峰python教程学习之习题解析相关推荐

  1. Python 3 学习(一)—— 基础:廖雪峰 Python 教程学习笔记

    文章目录 Python教程 值类型和引用类型 列表和字典的基本操作 列表 元组 字典 Set 函数 内置函数 定义函数 空函数 参数检查 定义默认参数要牢记一点:默认参数必须指向不变对象! Pytho ...

  2. 廖雪峰python教程学习:装饰器@小结

    装饰器@小结 廖雪峰老师的python教程 在代码运行期间动态增加功能的方式,称为装饰器 本质上,装饰器是一个可以返回函数的高阶函数 最基本的可以定义如下: def log(func):@functo ...

  3. 廖雪峰python教程学习:类、实例与数据封装小结

    类.实例与数据封装小结 廖雪峰老师的python教程 1.类与实例 面向对象最重要的内容就是类(class),类是抽象的模板,后面紧接着是类名,紧接着是(object),表示其是从哪个类上继承上来的, ...

  4. 廖雪峰Python教程-笔记

    廖雪峰Python教程 学习范围: Python基础 函数 高级特性 函数性编程 模块 面向对象编程 错误,调试和测试 IO编程 笔记: Python的整数没有大小限制 Python 3的字符串使用U ...

  5. 廖雪峰python教程视频-为什么看不懂廖雪峰的Python学习教程?

    廖雪峰的Python教程已经很友好了,接近于把饭喂到嘴边了. 这不是廖雪峰教程的问题,而是一个基础代码技能和实际应用需求的代码技能差距太远导致的. 如果是新手,只学会了廖雪峰Python教程,那约等于 ...

  6. 廖雪峰python教程完整版-为什么看不懂廖雪峰的Python学习教程?

    廖雪峰的Python教程已经很友好了,接近于把饭喂到嘴边了. 这不是廖雪峰教程的问题,而是一个基础代码技能和实际应用需求的代码技能差距太远导致的. 如果是新手,只学会了廖雪峰Python教程,那约等于 ...

  7. 廖雪峰Python教程 实战day05

    廖雪峰Python教程 实战day05 1. Web程序工作流程 本文部分文字内容.图片摘自<Flask Web开发实战:入门.进阶与原理解析>,作者李辉. 在编写自己的Web框架之前,首 ...

  8. 廖雪峰python教程在哪看_:廖雪峰python教程在哪

    标签,你可以自己查看网页源代码. 廖雪峰的python教程有一点地方没看明白,求指导 题主贴了函数,似乎是一样的,就分析这一个版本:def add_end(L=None): if L is None: ...

  9. 会python再学java要多久_【学过python多久能学会java】廖雪峰python教程要学多久

    自学完廖雪峰python可以找到相关工作吗? 如果只是学完廖雪峰的教程我觉得是不够的,你必须对一些方面有更加深入的实践和学习.我是工作中需要用到python,看了廖雪峰的教程,实现快速开发. 学过py ...

最新文章

  1. Lock free queue 大比拼
  2. Spring-Data-MongoDB的Index注解的expireAfterSeconds参数不起作用?解决方案居然是这样的!...
  3. Michael Jordan:当下的AI其实都是伪“AI” 1
  4. MiniO对象存储服务 磁盘缓存快速入门 ​​​​​​​
  5. Python和java二选一该学啥
  6. pr自学教程,为丢失的镜头注入新的活力
  7. 15种排序算法可视化展示
  8. bat执行cmd命令_kettle定时任务pan.bat和kitchen.bat
  9. springboot整合富文本编辑器
  10. 51单片机简易智能温度检测系统
  11. 一文搞懂机器学习准确率(Accuracy)、精确率(Pecision)、召回率(Recall)以及TP、FP、TN、FN
  12. The coordinates or measures are out of bounds.
  13. 深入浅出java web_深入浅出javaWeb实战第1讲Web的概念及其演变(上)
  14. 一种有趣的弱监督机器学习问题:比例标签学习(Learning from label proportions)
  15. git提交代码失败 ‘“node“‘ �����ڲ����ⲿ���Ҳ���ǿ����еij������������ļ��� 解决方法
  16. 关于XD卡写保护问题!
  17. 触摸屏键盘插件Virtual Keyboard 该怎么用 Virtual Keyboard 入门指南
  18. 生活污水处理设备让污水无处躲藏
  19. 500+分区Mini LED,海信电视E8H让画质更纯净
  20. linux who命令详解,Linux who命令详解

热门文章

  1. eDiary 个人日记本使用技巧
  2. (5)数据库—----单行函数—------字符函数、数学函数、日期函数
  3. 《你好啊,程序员》学习笔记
  4. week-14(时间管理带师)
  5. Lesson 018 —— python 集合
  6. UE4添加视频——手把手吧
  7. android开发笔记之com.android.support:percent
  8. 《性格色彩》测试加分析
  9. 数据安全前言技术研究联邦学习
  10. 虚拟机如何使用共享文件夹传文件