python学习网站

学习Python无从下手?最好的免费资源想要拿走

https://baijiahao.baidu.com/s?id=1609921358863871939&wfr=spider&for=pc

一个牛逼的 Python 调试工具 PySnooper

https://www.jianshu.com/p/3848865e520e

廖雪峰的官方网站

https://www.liaoxuefeng.com/          python语言基础

 

python练习题答案

Python教程--廖雪峰练习参考汇总(一)
原创树街猫 发布于2018-05-26 19:10:46 阅读数 1415 收藏
展开
题源:廖老师的官网
小生全是为了方便后期代码整理,从多篇大佬中的文章引用了代码,如有冒犯之处,请联系小生。

练习
小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出’xx.x%’,只保留小数点后1位:

# -*- coding: utf-8 -*-
s1 = 72
s2 = 85
r = 100*(s2-s1)/s1
print('提高了''%.1f%%' % r)
1
2
3
4
5
练习
小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
低于18.5:过轻
18.5-25:正常
25-28:过重
28-32:肥胖
高于32:严重肥胖
用if-elif判断并打印结果:

# -*- coding: utf-8 -*-

height = 1.75
weight = 80.5bmi = weight / height / height
if bmi < 18.5:
print ('过轻')
elif bmi >= 18.5 and bmi < 25:
print ('正常')
elif bmi >= 25 and bmi < 28:
print ('过重')
elif bmi >= 28 and bmi <32:
print ('肥胖')
else:
print ('严重肥胖')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
练习
请利用循环依次对list中的每个名字打印出Hello, xxx!:

# -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Adam']
for i in L:
print('Hello,',i,'!')
1
2
3
4
5
练习
请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串:

# -*- coding: utf-8 -*-

n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
1
2
3
4
5
6
练习
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax2 + bx + c = 0
的两个解。
提示:计算平方根可以调用math.sqrt()函数。

# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
L=((-b+math.sqrt(b*b-4*a*c))/(2*a),(-b-math.sqrt(b*b-4*a*c))/(2*a))
return L

# 测试:
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('测试成功')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
练习
以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:
【转】

# -*- coding: utf-8 -*-
def product(*numbers): #定义一个函数
if numbers is None or len(numbers)<=0 :
raise TypeError("args not null!") #将函数提前给定好各种情况,如果小于零,等于零或者未输入
sum = 1
for n in numbers:
sum = sum *n #如果n在给定的数列中,那么就将sum*每一个数值得出总数
return sum
# 测试
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
product()
print('测试失败!')
except TypeError:
print('测试成功!')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
练习
汉诺塔的移动可以用递归函数非常简单地实现。
请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法,例如:

# -*- coding: utf-8 -*-
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)
# 期待输出:
# A --> C
# A --> B
# C --> B
# A --> C
# B --> A
# B --> C
# A --> C
move(3, 'A', 'B', 'C')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
练习
利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:

# -*- coding: utf-8 -*-
def trim(s):
if len(s) == 0:
return s
elif s[0] == ' ':
return (trim(s[1:]))
elif s[-1] == ' ':
return (trim(s[:-1]))
return s

# 测试:
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
练习–迭代
请使用迭代查找一个list中最小和最大值,并返回一个tuple:【转 忘了哪位的了~】

def trim(s):
#'''首先判断该字符串是否为空,如果为空,就返回该字符串,
#如果不为空的话,就判断字符串首尾字符是否为空,
#如果为空,就使用递归再次调用该函数trim(),否则就返回该函数'''
if len(s) == 0:
return s
elif s[0] == ' ':
return (trim(s[1:]))
elif s[-1] == ' ':
return (trim(s[:-1]))
return s


# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:


>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
1
2
3
4
5
6
7
使用内建的isinstance函数可以判断一个变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
1
2
3
4
5
6
请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:

# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[]
for i in L1:
if isinstance(i,str)==True:
L2.append(i.lower())

# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:
print('测试通过!')
else:
print('测试失败!')
1
2
3
4
5
6
7
8
9
10
11
12
13
练习
杨辉三角定义如下:

把每一行看做一个list,试写一个generator,不断输出下一行的list:


# -*- coding: utf-8 -*-
def triangles():
L = [1]
while True:
yield L[:len(L)]
L.append(0)
L = [L[i - 1] + L[i] for i in range(len(L))]

def main():
n = 0
results = []
for x in triangles():
print(x)
results.append(x)
n = n + 1
if n == 10:
break

if results == [
[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]
]:
print("测试成功!")
else:
print("测试失败!")

for y in results:
print(y)

main()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
练习
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]:

# -*- coding: utf-8 -*-
def normalize(name):
return "%s" % (inStr[:1].upper() + inStr[1:].lower())

 

 

# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
1
2
3
4
5
6
7
8
9
10
Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:

# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):

return reduce(lambda x, y: x*y, L)

#来自 <https://www.cnblogs.com/taoleilei/articles/5461635.html>

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
1
2
3
4
5
6
7
8
9
10
11
12
13
利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456

# -*- coding: utf-8 -*-
# [转](https://blog.csdn.net/alicegotoanother/article/details/79066040)
from functools import reduce
def str2float(s):
def str2num(s):
return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]
def fnMuti(x,y):
return x*10 + y
def fnDivid(x,y):
return x/10 + y
dotIndex = s.index('.')
return reduce(fnMuti,map(str2num,s[:dotIndex])) + reduce(fnDivid,list(map(str2num,s[dotIndex+1:]))[::-1])/10
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')

posted @ 2019-12-23 11:35  mingli  阅读(296)  评论(0编辑  收藏  举报