• 值得收藏的30道Python练手题(附详解)


    今天给大家分享30道Python练习题,建议大家先独立思考一下解题思路,再查看答案。

    1. 已知一个字符串为 “hello_world_yoyo”,如何得到一个队列 [“hello”,”world”,”yoyo”] ?

    使用 split 函数,分割字符串,并且将数据转换成列表类型:

    1. test = 'hello_world_yoyo'
    2. print(test.split("_"))
    3. 12

    结果:

    ['hello''world''yoyo']

    2. 有个列表 [“hello”, “world”, “yoyo”],如何把列表里面的字符串联起来,得到字符串 “hello_world_yoyo”?

    使用 join 函数将数据转换成字符串:

    1. test = ["hello""world""yoyo"]
    2. print("_".join(test))

    结果:

    hello_world_yoyo
    

    如果不依赖 python 提供的 join 方法,还可以通过 for 循环,然后将字符串拼接,但是在用“+”连接字符串时,结果会生成新的对象,使用 join 时结果只是将原列表中的元素拼接起来,所以 join 效率比较高。

    for 循环拼接如下:

    1. test = ["hello""world""yoyo"]
    2. # 定义一个空字符串
    3. j = ''
    4. # 通过 for 循环打印出列表中的数据
    5. for i in test:
    6.     j = j + "_" + i
    7. # 因为通过上面的字符串拼接,得到的数据是“_hello_world_yoyo”,前面会多一个下划线_,所以把这个下划线去掉
    8. print(j.lstrip("_"))

    3. 把字符串 s 中的每个空格替换成”%20”,输入:s = “We are happy.”,输出:“We%20are%20happy.”。

    使用 replace 函数,替换字符换即可:

    1. s = 'We are happy.'
    2. print(s.replace(' ''%20'))
    3. 12

    结果:

    We%20are%20happy.
    

    4. Python 如何打印 99 乘法表?

    for 循环打印:

    1. for i in range(110):
    2.     for j in range(1, i+1):
    3.         print('{}x{}={}\t'.format(j, i, i*j), end='')
    4.     print()

    while 循环实现:

    1. i = 1
    2. while i <= 9:
    3.     j = 1
    4.     while j <= i:
    5.         print("%d*%d=%-2d"%(i,j,i*j),end = ' ')  # %d: 整数的占位符,'-2'代表靠左对齐,两个占位符
    6.         j += 1
    7.     print()
    8.     i += 1

    结果:

    1. 1x1=1 
    2. 1x2=2 2x2=4 
    3. 1x3=3 2x3=6 3x3=9 
    4. 1x4=4 2x4=8 3x4=12 4x4=16 
    5. 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 
    6. 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 
    7. 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 
    8. 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 
    9. 1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

    5. 从下标 0 开始索引,找出单词 “welcome” 在字符串“Hello, welcome to my world.” 中出现的位置,找不到返回 -1。

    1. def test():
    2.     message = 'Hello, welcome to my world.'
    3.     world = 'welcome'
    4.     if world in message:
    5.         return message.find(world)
    6.     else:
    7.         return -1
    8. print(test())
    9. 结果:
    10. 7

    6. 统计字符串“Hello, welcome to my world.” 中字母 w 出现的次数。

    1. def test():
    2.     message = 'Hello, welcome to my world.'
    3.     # 计数
    4.     num = 0
    5.     # for 循环 message
    6.     for i in message:
    7.         # 判断如果 ‘w’ 字符串在 message 中,则 num +1
    8.         if 'w' in i:
    9.             num += 1
    10.     return num
    11. print(test())
    12. # 结果
    13. 2

    7. 输入一个字符串 str,输出第 m 个只出现过 n 次的字符,如在字符串 gbgkkdehh 中,找出第 2 个只出现 1 次的字符,输出结果:d

    1. def test(str_test, num, counts):
    2.     """
    3.     :param str_test: 字符串
    4.     :param num: 字符串出现的次数
    5.     :param count: 字符串第几次出现的次数
    6.     :return:
    7.     """
    8.     # 定义一个空数组,存放逻辑处理后的数据
    9.     list = []
    10.     # for循环字符串的数据
    11.     for i in str_test:
    12.         # 使用 count 函数,统计出所有字符串出现的次数
    13.         count = str_test.count(i, 0len(str_test))
    14.         # 判断字符串出现的次数与设置的counts的次数相同,则将数据存放在list数组中
    15.         if count == num:
    16.             list.append(i)
    17.     # 返回第n次出现的字符串
    18.     return list[counts-1]
    19. print(test('gbgkkdehh'12))
    20. 结果:
    21. d

    8. 判断字符串 a = “welcome to my world” 是否包含单词 b = “world”,包含返回 True,不包含返回 False。

    1. def test():
    2.     message = 'welcome to my world'
    3.     world = 'world'
    4.     if world in message:
    5.         return True
    6.     return False
    7. print(test())
    8. 结果:
    9. True

    9. 从 0 开始计数,输出指定字符串 A = “hello” 在字符串 B = “hi how are you hello world, hello yoyo!”中第一次出现的位置,如果 B 中不包含 A,则输出 -1。

    1. def test():
    2.     message = 'hi how are you hello world, hello yoyo!'
    3.     world = 'hello'
    4.     return message.find(world)
    5. print(test())
    6. 结果:
    7. 15

    10. 从 0 开始计数,输出指定字符串 A = “hello”在字符串 B = “hi how are you hello world, hello yoyo!”中最后出现的位置,如果 B 中不包含 A,则输出 -1。

    1. def test(string, str):
    2.     # 定义 last_position 初始值为 -1
    3.     last_position = -1
    4.     while True:
    5.         position = string.find(str, last_position+1)
    6.         if position == -1:
    7.             return last_position
    8.         last_position = position
    9. print(test('hi how are you hello world, hello yoyo!''hello'))
    10. 结果:
    11. 28

    11. 给定一个数 a,判断一个数字是否为奇数或偶数。

    1. while True:
    2.     try:
    3.         # 判断输入是否为整数
    4.         num = int(input('输入一个整数:'))
    5.     # 不是纯数字需要重新输入
    6.     except ValueError: 
    7.         print("输入的不是整数!")
    8.         continue
    9.     if num % 2 == 0:
    10.         print('偶数')
    11.     else:
    12.         print('奇数')
    13.     break
    14. 结果:
    15. 输入一个整数:100
    16. 偶数

    12. 输入一个姓名,判断是否姓王。

    1. def test():
    2.     user_input = input("请输入您的姓名:")
    3.     if user_input[0] == '王':
    4.         return "用户姓王"
    5.     return "用户不姓王"
    6. print(test())
    7. 结果:
    8. 请输入您的姓名:王总
    9. 用户姓王

    13. 如何判断一个字符串是不是纯数字组成?

    利用 Python 提供的类型转行,将用户输入的数据转换成浮点数类型,如果转换抛异常,则判断数字不是纯数字组成。

    1. def test(num):
    2.     try:
    3.         return float(num)
    4.     except ValueError:
    5.         return "请输入数字"
    6. print(test('133w3'))

    14. 将字符串 a = “This is string example….wow!” 全部转成大写,字符串 b = “Welcome To My World” 全部转成小写。

    1. a = 'This is string example….wow!'
    2. b = 'Welcome To My World'
    3. print(a.upper())
    4. print(b.lower())

    15. 将字符串 a = “ welcome to my world ”首尾空格去掉

    Python 提供了strip() 方法,可以去除首尾空格,rstrip() 去掉尾部空格,lstrip() 去掉首部空格,replace(" ", “”) 去掉全部空格。

    1. a = '  welcome to my world   '
    2. print(a.strip())

    还可以通过递归的方式实现:

    1. def trim(s):
    2.     flag = 0
    3.     if s[:1]==' ':
    4.         s = s[1:]
    5.         flag = 1
    6.     if s[-1:] == ' ':
    7.         s = s[:-1]
    8.         flag = 1
    9.     if flag==1:
    10.         return    trim(s)
    11.     else:
    12.         return s
    13. print(trim('  Hello world!  '))

    通过 while 循环实现:

    1. def trim(s):
    2.     while(True):
    3.         flag = 0
    4.         if s[:1]==' ':
    5.             s = s[1:]
    6.             flag = 1
    7.         if s[-1:] == ' ':
    8.             s = s[:-1]
    9.             flag = 1
    10.         if flag==0:
    11.             break
    12.     return s
    13. print(trim('  Hello world!  '))

    16. 将字符串 s = “ajldjlajfdljfddd”,去重并从小到大排序输出”adfjl”。

    1. def test():
    2.     s = 'ajldjlajfdljfddd'
    3.     # 定义一个数组存放数据
    4.     str_list = []
    5.     # for循环s字符串中的数据,然后将数据加入数组中
    6.     for i in s:
    7.         # 判断如果数组中已经存在这个字符串,则将字符串移除,加入新的字符串
    8.         if i in str_list:
    9.             str_list.remove(i)
    10.         str_list.append(i)
    11.     # 使用 sorted 方法,对字母进行排序
    12.     a = sorted(str_list)
    13.     # sorted方法返回的是一个列表,这边将列表数据转换成字符串
    14.     return "".join(a)
    15. print(test())
    16. 结果:
    17. adfjl

    17. 打印出如下图案(菱形):

    1. def test():
    2.     n = 8
    3.     for i in range(-int(n/2), int(n/2) + 1):
    4.         print(" "*abs(i), "*"*abs(n-abs(i)*2))
    5. print(test())
    6. 结果:
    7.     **
    8.    ****
    9.   ******
    10.  ********
    11.   ******
    12.    ****
    13.     **

    18.  给一个不多于 5 位的正整数(如 a = 12346),求它是几位数和逆序打印出各位数字。

    1. class Test:
    2.     # 计算数字的位数
    3.     def test_num(self, num):
    4.         try:
    5.             # 定义一个 length 的变量,来计算数字的长度
    6.             length = 0
    7.             while num != 0:
    8.                 # 判断当 num 不为 0 的时候,则每次都除以10取整
    9.                 length += 1
    10.                 num = int(num) // 10
    11.             if length > 5:
    12.                 return "请输入正确的数字"
    13.             return length
    14.         except ValueError:
    15.             return "请输入正确的数字"
    16.     # 逆序打印出个位数
    17.     def test_sorted(self, num):
    18.         if self.test_num(num) != "请输入正确的数字":
    19.             # 逆序打印出数字
    20.             sorted_num = num[::-1]
    21.             # 返回逆序的个位数
    22.             return sorted_num[-1]
    23. print(Test().test_sorted('12346'))
    24. 结果:
    25. 1

    19. 如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。例如:153 = 13 + 53 + 33,因此 153 就是一个水仙花数。那么如何求 1000 以内的水仙花数(3 位数)。

    1. def test():
    2.     for num in range(1001000):
    3.         i = num // 100
    4.         j = num // 10 % 10
    5.         k = num % 10
    6.         if i ** 3 + j ** 3 + k ** 3 == num:
    7.             print(str(num) + "是水仙花数")
    8. test()

    20. 求 1+2+3…+100 相加的和。

    1. i = 1
    2. for j in range(101):
    3.     i = j + i
    4. print(i)
    5. 结果:
    6. 5051

    21. 计算 1-2+3-4+5-…-100 的值。

    1. def test(sum_to):
    2.     
    3.     # 定义一个初始值
    4.     sum_all = 0
    5.     # 循环想要计算的数据
    6.     for i in range(1, sum_to + 1):
    7.         sum_all += i * (-1) ** (1 + i)
    8.     return sum_all
    9. if __name__ == '__main__':
    10.     result = test(sum_to=100)
    11.     print(result)
    12. -50

    22. 现有计算公式 13 + 23 + 33 + 43 + …….+ n3,如何实现:当输入 n = 5 时,输出 225(对应的公式 : 13 + 23 + 33 + 43 + 53 = 225)。

    1. def test(n):
    2.     sum = 0
    3.     for i in range(1, n+1):
    4.         sum += i*10+i
    5.     return sum
    6. print(test(5))
    7. 结果:
    8. 225

    23. 已知 a 的值为“hello”,b 的值为“world”,如何交换 a 和 b 的值,得到 a 的值为“world”,b 的值为”hello”?

    1. a = 'hello'
    2. b = 'world'
    3. c = a
    4. a = b
    5. b = c
    6. print(a, b)

    24. 如何判断一个数组是对称数组?

    例如 [1,2,0,2,1],[1,2,3,3,2,1],这样的数组都是对称数组。用 Python 判断,是对称数组打印 True,不是打印 False。

    1. def test():
    2.     x = [1'a'0'2'0'a'1]
    3.     # 通过下标的形式,将字符串逆序进行比对
    4.     if x == x[::-1]:
    5.         return True
    6.     return False
    7. print(test())
    8. 结果:
    9. True

    25. 如果有一个列表 a = [1,3,5,7,11],那么如何让它反转成 [11,7,5,3,1],并且取到奇数位值的数字 [1,5,11]?

    1. def test():
    2.     a = [1, 3, 5, 7, 11]
    3.     # 逆序打印数组中的数据
    4.     print(a[::-1])
    5.     # 定义一个计数的变量
    6.     count = 0
    7.     for i in a:
    8.         # 判断每循环列表中的一个数据,则计数器中会 +1
    9.         count += 1
    10.         # 如果计数器为奇数,则打印出来
    11.         if count % 2 != 0:
    12.             print(i)
    13. test()
    14. 结果:
    15. [11, 7, 5, 3, 1]
    16. 1
    17. 5
    18. 11

    26. 对列表 a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] 中的数字从小到大排序。

    1. a = [168119186878]
    2. print(sorted(a))
    3. 结果:
    4. [116678888911]

    27. 找出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大值和最小值。

    1. L1 = [12311253253388]
    2. print(max(L1))
    3. print(min(L1))
    4. 结果:
    5. 88
    6. 1

    上面是通过 Python 自带的函数实现,如下,可以自己写一个计算程序:

    1. class Test(object):
    2.     def __init__(self):
    3.         # 测试的列表数据
    4.         self.L1 = [12311253253388]
    5.         # 从列表中取第一个值,对于数据大小比对
    6.         self.num = self.L1[0]
    7.     def test_small_num(self, count):
    8.         """
    9.         :param count: count为 1,则表示计算最大值,为 2 时,表示最小值
    10.         :return:
    11.         """
    12.         # for 循环查询列表中的数据
    13.         for i in self.L1:
    14.             if count == 1:
    15.                 # 循环判断当数组中的数据比初始值小,则将初始值替换
    16.                 if i > self.num:
    17.                     self.num = i
    18.             
    19.             elif count == 2:
    20.                 if i < self.num:
    21.                     self.num = i
    22.                     
    23.             elif count != 1 or count != 2:
    24.                 return "请输入正确的数据"
    25.         return self.num
    26. print(Test().test_small_num(1))
    27. print(Test().test_small_num(2))
    28. 结果:
    29. 88
    30. 1

    28. 找出列表 a = [“hello”, “world”, “yoyo”, “congratulations”] 中单词最长的一个。

    1. def test():
    2.     a = ["hello""world""yoyo""congratulations"]
    3.     
    4.     # 统计数组中第一个值的长度
    5.     length = len(a[0])
    6.     
    7.     for i in a:
    8.         # 循环数组中的数据,当数组中的数据比初始值length中的值长,则替换掉length的默认值
    9.         if len(i) > length:
    10.             length = i
    11.     return length
    12. print(test())
    13. 结果:
    14. congratulations

    29. 取出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大的三个值。

    1. def test():
    2.     L1 = [12311253253388]
    3.     return sorted(L1)[:3]
    4. print(test())
    5. 结果:
    6. [122]

    30. 把列表 a = [1, -6, 2, -5, 9, 4, 20, -3] 中的数字绝对值。

    1. def test():
    2.     a = [1, -62, -59420, -3]
    3.     # 定义一个数组,存放处理后的绝对值数据
    4.     lists = []
    5.     for i in a:
    6.      # 使用 abs() 方法处理绝对值
    7.         lists.append(abs(i))
    8.     return lists
    9. print(test())
    10. 结果:
    11. [162594203]

    【python学习】
    学Python的伙伴,欢迎加入新的交流【君羊】:1020465983
    一起探讨编程知识,成为大神,群里还有软件安装包,实战案例、学习资料 

  • 相关阅读:
    kubernetesr进阶--污点和容忍之概述
    经典卷积神经网络模型 - InceptionNet
    基于Python的房屋租赁管理系统(附源码)
    使用VBS编写xshell/SecureCRT自动化脚本
    ffmpeg的安装以及使用
    OpenCV-Java 开发简介
    安装WordPress(个人建站)
    web期末作业设计网页 HTML+CSS+JavaScript仿王者荣耀游戏新闻咨询(网页设计期末课程设计)
    微服务实战 05 分布式事务 入门
    微信小程序&会议OA-登录获取手机号流程&登录-小程序&导入微信小程序SDK(从微信小程序和会议OA登录获取手机号到登录小程序导入微信小程序SDK)
  • 原文地址:https://blog.csdn.net/weixin_56659172/article/details/126136575