> 技术文档 > 【Python练习题】Python小白必练100题答案-第21-40题

【Python练习题】Python小白必练100题答案-第21-40题

练习题 直达链接 Python小白必练100题答案-第1-20题 点我直达 Python小白必练100题答案-第41-60题 点我直达

目录

    • 专栏导读
    • 循环结构 + 字符串操作
    • 第三部分:循环结构 (21-30题)
      • 21. 数字累加
      • 22. 乘法表
      • 23. 阶乘计算
      • 24. 斐波那契数列
      • 25. 素数判断
      • 26. 猜数字游戏
      • 27. 水仙花数
      • 28. 倒序输出
      • 29. 数字统计
      • 30. 完数判断
    • 第四部分:字符串操作 (31-40题)
      • 31. 字符串长度
      • 32. 字符串反转
      • 33. 回文判断
      • 34. 字符统计
      • 35. 大小写转换
      • 36. 单词计数
      • 37. 字符串查找
      • 38. 字符串替换
      • 39. 首字母大写
      • 40. 去除空格
    • 总结
      • 循环结构 (21-30题)
      • 字符串操作 (31-40题)

专栏导读

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

循环结构 + 字符串操作


第三部分:循环结构 (21-30题)

21. 数字累加

题目: 计算1到100的和

答案:

def sum_1_to_100(): total = 0 for i in range(1, 101): total += i return totalresult = sum_1_to_100()print(f\"1到100的和:{result}\")# 验证公式:n*(n+1)/2print(f\"公式验证:{100*101//2}\")

输出:

1到100的和:5050公式验证:5050

22. 乘法表

题目: 输出九九乘法表

答案:

def multiplication_table(): for i in range(1, 10): for j in range(1, i+1): print(f\"{j}×{i}={i*j}\", end=\"\\t\") print() # 换行print(\"九九乘法表:\")multiplication_table()

输出:

九九乘法表:1×1=11×2=22×2=41×3=32×3=63×3=91×4=42×4=83×4=124×4=16...

23. 阶乘计算

题目: 计算数字的阶乘

答案:

def factorial(n): if n <= 1: return 1 result = 1 for i in range(2, n+1): result *= i return resulttest_nums = [5, 0, 1, 7]for num in test_nums: print(f\"{num}! = {factorial(num)}\")

输出:

5! = 1200! = 11! = 17! = 5040

24. 斐波那契数列

题目: 生成斐波那契数列

答案:

def fibonacci(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] fib_list = [0, 1] for i in range(2, n): fib_list.append(fib_list[i-1] + fib_list[i-2]) return fib_listn = 10fib_sequence = fibonacci(n)print(f\"斐波那契数列前{n}项:{fib_sequence}\")

输出:

斐波那契数列前10项:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

25. 素数判断

题目: 判断一个数是否为素数

答案:

import mathdef is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return Truetest_nums = [2, 3, 4, 17, 25, 29]for num in test_nums: result = \"是\" if is_prime(num) else \"不是\" print(f\"{num} {result}素数\")

输出:

2 是素数3 是素数4 不是素数17 是素数25 不是素数29 是素数

26. 猜数字游戏

题目: 实现猜数字游戏

答案:

import randomdef guess_number_game(): target = random.randint(1, 100) print(f\"计算机生成的数字是:{target}(实际游戏中不显示)\") # 模拟几次猜测 guesses = [50, 75, 88, target] # 模拟猜测过程 attempts = 0 for guess in guesses: attempts += 1 if guess == target: print(f\"第{attempts}次猜测:{guess} - 恭喜!猜对了!\") break elif guess < target: print(f\"第{attempts}次猜测:{guess} - 太小了!\") else: print(f\"第{attempts}次猜测:{guess} - 太大了!\")guess_number_game()

输出:

计算机生成的数字是:92(实际游戏中不显示)第1次猜测:50 - 太小了!第2次猜测:75 - 太小了!第3次猜测:88 - 太小了!第4次猜测:92 - 恭喜!猜对了!

27. 水仙花数

题目: 找出所有三位水仙花数

答案:

def find_narcissistic_numbers(): narcissistic_nums = [] for num in range(100, 1000): digits = [int(d) for d in str(num)] if sum(d**3 for d in digits) == num: narcissistic_nums.append(num) return narcissistic_numsnarcissistic_nums = find_narcissistic_numbers()print(f\"所有三位水仙花数:{narcissistic_nums}\")

输出:

所有三位水仙花数:[153, 371, 407]

28. 倒序输出

题目: 将数字倒序输出

答案:

def reverse_number(n): reversed_num = 0 while n > 0: reversed_num = reversed_num * 10 + n % 10 n //= 10 return reversed_numtest_nums = [12345, 6789, 100]for num in test_nums: print(f\"{num} 倒序后:{reverse_number(num)}\")

输出:

12345 倒序后:543216789 倒序后:9876100 倒序后:1

29. 数字统计

题目: 统计数字中各位数字出现的次数

答案:

def count_digits(n): digit_count = {} for digit in str(n): digit_count[digit] = digit_count.get(digit, 0) + 1 return digit_counttest_nums = [112233, 123321, 555666]for num in test_nums: counts = count_digits(num) print(f\"{num} 各数字出现次数:{counts}\")

输出:

112233 各数字出现次数:{\'1\': 2, \'2\': 2, \'3\': 2}123321 各数字出现次数:{\'1\': 2, \'2\': 2, \'3\': 2}555666 各数字出现次数:{\'5\': 3, \'6\': 3}

30. 完数判断

题目: 判断完数并找出范围内的所有完数

答案:

def is_perfect_number(n): if n <= 1: return False divisors_sum = 0 for i in range(1, n): if n % i == 0: divisors_sum += i return divisors_sum == ndef find_perfect_numbers(limit): perfect_nums = [] for num in range(1, limit + 1): if is_perfect_number(num): perfect_nums.append(num) return perfect_numsperfect_nums = find_perfect_numbers(1000)print(f\"1000以内的完数:{perfect_nums}\")

输出:

1000以内的完数:[6, 28, 496]

第四部分:字符串操作 (31-40题)

31. 字符串长度

题目: 计算字符串长度(不使用内置函数)

答案:

def string_length(s): count = 0 for char in s: count += 1 return counttest_strings = [\"Hello\", \"Python编程\", \"\"]for s in test_strings: print(f\"\'{s}\' 长度:{string_length(s)} (内置函数验证:{len(s)})\")

输出:

\'Hello\' 长度:5 (内置函数验证:5)\'Python编程\' 长度:8 (内置函数验证:8)\'\' 长度:0 (内置函数验证:0)

32. 字符串反转

题目: 反转字符串

答案:

def reverse_string(s): reversed_str = \"\" for char in s: reversed_str = char + reversed_str return reversed_strtest_strings = [\"Hello\", \"Python\", \"12345\"]for s in test_strings: print(f\"\'{s}\' 反转后:\'{reverse_string(s)}\'\")

输出:

\'Hello\' 反转后:\'olleH\'\'Python\' 反转后:\'nohtyP\'\'12345\' 反转后:\'54321\'

33. 回文判断

题目: 判断字符串是否为回文

答案:

def is_palindrome(s): # 转换为小写并去除空格 s = s.lower().replace(\" \", \"\") return s == s[::-1]test_strings = [\"level\", \"hello\", \"A man a plan a canal Panama\", \"race a car\"]for s in test_strings: result = \"是\" if is_palindrome(s) else \"不是\" print(f\"\'{s}\' {result}回文\")

输出:

\'level\' 是回文\'hello\' 不是回文\'A man a plan a canal Panama\' 是回文\'race a car\' 不是回文

34. 字符统计

题目: 统计字符串中字母、数字、空格和其他字符的个数

答案:

def count_characters(s): letters = 0 digits = 0 spaces = 0 others = 0 for char in s: if char.isalpha(): letters += 1 elif char.isdigit(): digits += 1 elif char.isspace(): spaces += 1 else: others += 1 return letters, digits, spaces, otherstest_string = \"Hello World 123 !\"letters, digits, spaces, others = count_characters(test_string)print(f\"字符串:\'{test_string}\'\")print(f\"字母:{letters}个,数字:{digits}个,空格:{spaces}个,其他:{others}个\")

输出:

字符串:\'Hello World 123 !\'字母:10个,数字:3个,空格:3个,其他:1个

35. 大小写转换

题目: 将字符串中的大小写字母互换

答案:

def swap_case(s): result = \"\" for char in s: if char.isupper(): result += char.lower() elif char.islower(): result += char.upper() else: result += char return resulttest_strings = [\"Hello World\", \"PyThOn ProGramming\"]for s in test_strings: print(f\"\'{s}\' -> \'{swap_case(s)}\'\")

输出:

\'Hello World\' -> \'hELLO wORLD\'\'PyThOn ProGramming\' -> \'pYtHoN pROgRAMMING\'

36. 单词计数

题目: 统计字符串中单词的个数

答案:

def count_words(text): words = text.split() return len(words)test_texts = [ \"Hello world\", \"Python is a great programming language\", \" Multiple spaces between words \"]for text in test_texts: print(f\"\'{text}\' 包含 {count_words(text)} 个单词\")

输出:

\'Hello world\' 包含 2 个单词\'Python is a great programming language\' 包含 6 个单词\' Multiple spaces between words \' 包含 4 个单词

37. 字符串查找

题目: 查找子字符串在主字符串中的所有位置

答案:

def find_substring(text, substring): positions = [] start = 0 while True: pos = text.find(substring, start) if pos == -1: break positions.append(pos) start = pos + 1 return positionstext = \"hello world hello python hello\"substring = \"hello\"positions = find_substring(text, substring)print(f\"在 \'{text}\' 中查找 \'{substring}\'\")print(f\"找到位置:{positions}\")

输出:

在 \'hello world hello python hello\' 中查找 \'hello\'找到位置:[0, 12, 25]

38. 字符串替换

题目: 替换字符串中的指定字符

答案:

def replace_char(text, old_char, new_char): result = \"\" for char in text: if char == old_char: result += new_char else: result += char return resulttext = \"hello world\"old_char = \"l\"new_char = \"x\"result = replace_char(text, old_char, new_char)print(f\"\'{text}\' 将 \'{old_char}\' 替换为 \'{new_char}\': \'{result}\'\")

输出:

\'hello world\' 将 \'l\' 替换为 \'x\': \'hexxo worxd\'

39. 首字母大写

题目: 将字符串中每个单词的首字母大写

答案:

def capitalize_words(text): words = text.split() capitalized_words = [] for word in words: if word: capitalized_word = word[0].upper() + word[1:].lower() capitalized_words.append(capitalized_word) return \" \".join(capitalized_words)test_texts = [ \"hello world\", \"python programming language\", \"tHiS iS a TeSt\"]for text in test_texts: print(f\"\'{text}\' -> \'{capitalize_words(text)}\'\")

输出:

\'hello world\' -> \'Hello World\'\'python programming language\' -> \'Python Programming Language\'\'tHiS iS a TeSt\' -> \'This Is A Test\'

40. 去除空格

题目: 去除字符串首尾的空格

答案:

def strip_spaces(text): # 去除首尾空格 start = 0 end = len(text) - 1 # 找到第一个非空格字符 while start < len(text) and text[start] == \' \': start += 1 # 找到最后一个非空格字符 while end >= 0 and text[end] == \' \': end -= 1 if start > end: return \"\" return text[start:end+1]test_texts = [ \" hello world \", \" python \", \" \", \"no spaces\"]for text in test_texts: stripped = strip_spaces(text) print(f\"\'{text}\' -> \'{stripped}\' (长度:{len(text)} -> {len(stripped)})\")

输出:

\' hello world \' -> \'hello world\' (长度:17 -> 11)\' python \' -> \'python\' (长度:10 -> 6)\' \' -> \'\' (长度:3 -> 0)\'no spaces\' -> \'no spaces\' (长度:9 -> 9)

总结

第21-40题主要涵盖了Python的进阶知识:

循环结构 (21-30题)

  • 基础循环:for循环、while循环的使用
  • 数学计算:累加、阶乘、斐波那契数列
  • 算法应用:素数判断、水仙花数、完数
  • 数字处理:倒序、数字统计
  • 游戏编程:猜数字游戏的实现

字符串操作 (31-40题)

  • 基础操作:长度计算、反转、大小写转换
  • 字符分析:字符统计、回文判断
  • 文本处理:单词计数、查找替换
  • 格式化:首字母大写、去除空格
  • 算法思维:字符串搜索和处理算法

这些知识点为后续学习数据结构、算法和更复杂的编程概念打下了坚实的基础!

  • 希望对初学者有帮助;致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【❤️一个免费关注❤️】感谢!

  • 求个 🤞 关注 🤞 +❤️ 喜欢 ❤️ +👍 收藏 👍

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏