廖雪峰python教程学习之习题解析

第一天

条件判断练习测试

# 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
# 用if-elif判断并打印结果:

def exp_if():
    height = 1.75
    weight = 80.5
    bmi = 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+i
    i=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.14
    s=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=-5
    y=6
    f=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*x

def 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+y

def 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+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]

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=1
    for i in range(len(L)):
        sumL=sumL*L[i]
    return sumL

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')
from functools import reduce

def 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 == 1

L1 = 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=name
        self.score=score
    def 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=name
        self.__score=score
    def print_score(self):
        return '%s,%s'%(self.__name,self.__score)

    def get_name(self):
        return self.__name
    def 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 = name
        self.__gender = gender

    def get_gender(self):
        return self.__gender
    def set_gender(self,gender):
        self.__gender=gender
        return self.__gender

def 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 = 0

    def __init__(self, name):
        self.name = name
        Student.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 表示必须以数字结束

案例:正则匹配邮箱

test='[email protected]'
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()

未完待续…

猜你喜欢

转载自blog.csdn.net/sinat_34789167/article/details/81129040