30道Python练手题(附详解),编程菜鸟请收好~
30道Python练习题,建议大家先独立思考一下解题思路,再查看答案。1. 已知一个字符串为 “hello_world_yoyo”,如何得到一个队列 [“hello”,”world”,”yoyo”] ?使用 split 函数,分割字符串,并且将数据转换成列表类型:
test = 'hello_world<em>yoyo'print(test.split("</em>"))12
结果:
['hello', 'world', 'yoyo']
2. 有个列表 [“hello”, “world”, “yoyo”],如何把列表里面的字符串联起来,得到字符串 “hello_world_yoyo”?
使用 join 函数将数据转换成字符串:
test = ["hello", "world", "yoyo"]print("_".join(test))
结果:
hello_world_yoyo
3. 把字符串 s 中的每个空格替换成”%20”,输入:s = “We are happy.”,输出:“We%20are%20happy.”。
使用 replace 函数,替换字符换即可:
s = 'We are happy.'print(s.replace(' ', '%20'))12
4. Python 如何打印 99 乘法表?
for 循环打印:
for i in range(1, 10): for j in range(1, i+1): print('{}x{}={}\t'.format(j, i, i*j), end='') print()
while 循环实现:
i = 1while i 5: return "请输入正确的数字" return length except ValueError: return "请输入正确的数字" # 逆序打印出个位数 def test_sorted(self, num): if self.test_num(num) != "请输入正确的数字": # 逆序打印出数字 sorted_num = num[::-1] # 返回逆序的个位数 return sorted_num[-1]print(Test().test_sorted('12346'))结果:1
19. 如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。例如:153 = 13 + 53 + 33,因此 153 就是一个水仙花数。那么如何求 1000 以内的水仙花数(3 位数)。
def test(): for num in range(100, 1000): i = num // 100 j = num // 10 % 10 k = num % 10 if i ** 3 + j ** 3 + k ** 3 == num: print(str(num) + "是水仙花数")test()
20. 求 1+2+3…+100 相加的和。
i = 1for j in range(101): i = j + iprint(i)结果:5051
21. 计算 1-2+3-4+5-…-100 的值。
def test(sum_to): # 定义一个初始值 sum_all = 0 # 循环想要计算的数据 for i in range(1, sum_to + 1): sum_all += i * (-1) ** (1 + i) return sum_allif __name__ == '__main__': result = test(sum_to=100) print(result)-50
22. 现有计算公式 13 + 23 + 33 + 43 + …….+ n3,如何实现:当输入 n = 5 时,输出 225(对应的公式 : 13 + 23 + 33 + 43 + 53 = 225)。
def test(n): sum = 0 for i in range(1, n+1): sum += i*10+i return sumprint(test(5))结果:225
23. 已知 a 的值为“hello”,b 的值为“world”,如何交换 a 和 b 的值,得到 a 的值为“world”,b 的值为”hello”?
a = 'hello'b = 'world'c = aa = bb = cprint(a, b)
24. 如何判断一个数组是对称数组?
例如 [1,2,0,2,1],[1,2,3,3,2,1],这样的数组都是对称数组。用 Python 判断,是对称数组打印 True,不是打印 False。
def test(): x = [1, 'a', 0, '2', 0, 'a', 1] # 通过下标的形式,将字符串逆序进行比对 if x == x[::-1]: return True return Falseprint(test())结果:True
26. 对列表 a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] 中的数字从小到大排序。
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]print(sorted(a))结果:[1, 1, 6, 6, 7, 8, 8, 8, 8, 9, 11]
27. 找出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大值和最小值。
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]print(max(L1))print(min(L1))结果:881
29. 取出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大的三个值。
def test(): L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] return sorted(L1)[:3]print(test())结果:[1, 2, 2]
30. 把列表 a = [1, -6, 2, -5, 9, 4, 20, -3] 中的数字绝对值。
def test(): a = [1, -6, 2, -5, 9, 4, 20, -3] # 定义一个数组,存放处理后的绝对值数据 lists = [] for i in a: # 使用 abs() 方法处理绝对值 lists.append(abs(i)) return listsprint(test())结果:[1, 6, 2, 5, 9, 4, 20, 3]
转自:Python专栏