> 技术文档 > 值得苦练的100道Python经典练手题(全网最全,附详细答案,建议收藏)_python基础题库100题及答案

值得苦练的100道Python经典练手题(全网最全,附详细答案,建议收藏)_python基础题库100题及答案

在备考数据库系统工程师的过程中,Python作为一门强大的工具语言,能够帮助我们更高效地处理数据、实现算法和自动化任务。以下整理了100道Python经典练习题,涵盖基础语法、数据结构、数据库操作等多个方面,每道题都附有详细解析,建议收藏反复练习!

一、基础语法题(1-20)

1. 变量与数据类型

题目:定义三个变量a=10b=3.14c=\"Hello\",并分别打印它们的数据类型。

答案

a = 10b = 3.14c = \"Hello\"print(type(a)) # print(type(b)) # print(type(c)) # 
2. 条件语句

题目:输入一个整数,判断它是偶数还是奇数,并输出结果。

答案

num = int(input(\"请输入一个整数:\"))if num % 2 == 0: print(f\"{ num} 是偶数\")else: print(f\"{ num} 是奇数\")
3. 循环语句

题目:使用for循环打印1到10的整数。

答案

for i in range(1, 11): print(i)
4. 函数定义

题目:定义一个函数sum_numbers(a, b),返回两个数的和。

答案

def sum_numbers(a, b): return a + bresult = sum_numbers(5, 3)print(result) # 8
5. 列表操作

题目:创建一个包含5个元素的列表,然后删除第3个元素并打印列表。

答案

my_list = [10, 20, 30, 40, 50]del my_list[2]print(my_list) # [10, 20, 40, 50]
6. 字典操作

题目:创建一个字典存储学生信息(姓名、年龄、成绩),并打印所有键值对。

答案

student = { \"name\": \"张三\", \"age\": 20, \"score\": 85}for key, value in student.items(): print(f\"{ key}: { value}\")
7. 字符串处理

题目:将字符串\"hello world\"转换为大写并输出。

答案

s = \"hello world\"print(s.upper()) # HELLO WORLD
8. 异常处理

题目:编写代码尝试将字符串\"abc\"转换为整数,并捕获可能的异常。

答案

try: num = int(\"abc\")except ValueError as e: print(f\"错误:{ e}\") # 错误:invalid literal for int() with base 10: \'abc\'
9. 文件操作

题目:创建一个文本文件test.txt,写入\"Hello, Python!\",然后读取并打印内容。

答案

# 写入文件with open(\"test.txt\", \"w\") as f: f.write(\"Hello, Python!\")# 读取文件with open(\"test.txt\", \"r\") as f: content = f.read() print(content) # Hello, Python!
10. 列表推导式

题目:使用列表推导式生成1到10的平方列表。

答案

squares = [x**2 for x in range(1, 11)]print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
11. 元组操作

题目:创建一个元组(1, 2, 3),并尝试修改第二个元素为4(观察报错)。

答案

my_tuple = (1, 2, 3)try: my_tuple[1] = 4 # 报错:TypeError: \'tuple\' object does not support item assignmentexcept TypeError as e: print(f\"错误:{ e}\")
12. 集合操作

题目:创建两个集合set1 = {1, 2, 3}set2 = {3, 4, 5},求它们的交集和并集。

答案

set1 = { 1, 2, 3}set2 = { 3, 4, 5}intersection = set1 & set2 # {3}union = set1 | set2 # {1, 2, 3, 4, 5}print(intersection, union)
13. 函数参数

题目:定义一个函数print_info(name, age=18),使用默认参数和位置参数调用。

答案

def print_info(name, age=18): print(f\"{ name},年龄:{ age}\")print_info(\"张三\") # 张三,年龄:18print_info(\"李四\", 25) # 李四,年龄:25
14. 匿名函数

题目:使用匿名函数计算两个数的乘积。

答案

multiply = lambda x, y: x * yprint(multiply(3, 4)) # 12
15. 模块导入

题目:导入math模块,计算sqrt(16)sin(pi/2)

答案

import mathprint(math.sqrt(16)) # 4.0print(math.sin(math.pi/2)) # 1.0
16. 日期时间

题目:获取当前日期和时间,并格式化为YYYY-MM-DD HH:MM:SS

答案

from datetime import datetimenow = datetime.now()formatted = now.strftime(\"%Y-%m-%d %H:%M:%S\")print(formatted) # 例如:2023-05-10 14:30:00
17. 递归函数

题目:使用递归计算5的阶乘。

答案

def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1)print(factorial(5)) # 120
18. 列表排序

题目:对列表[3, 1, 4, 1, 5, 9, 2, 6]进行升序排序。

答案

my_list = [3, 1, 4, 1, 5, 9, 2, 6]my_list.sort()print(my_list) # [1, 1, 2, 3, 4, 5, 6, 9]
19. 条件表达式

题目:使用条件表达式实现:如果x > 5y = \"大\",否则y = \"小\"

答案

x = 7y = \"大\" if x > 5 else \"小\"print(y) # 大
20. 字符串切片

题目:提取字符串\"Python Programming\"的前6个字符。

答案

s = \"Python Programming\"print(s[:6]) # Python

二、数据结构题(21-40)

21. 栈的实现

题目:使用列表实现一个栈,支持pushpoppeek操作。

答案

class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() def peek(self): if not self.is_empty(): return self.items[-1] def is_empty(self): return len(self.items) == 0stack = Stack()stack.push(1)stack.push(2)print(stack.pop()) # 2print(stack.peek()) # 1
22. 队列的实现

题目:使用列表实现一个队列,支持enqueuedequeue操作。

答案

class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): if not self.is_empty(): return self.items.pop(0) def is_empty(self): return len(self.items) == 0queue = Queue()queue.enqueue(1)queue.enqueue(2)print(queue.dequeue()) # 1
23. 链表节点

题目:定义链表的节点类Node,包含数据和指向下一个节点的引用。

答案

class Node: def __init__(self, data): self.data = data self.next = Nonenode1 = Node(10)node2 = Node(20)node1.next = node2print(node1.data) # 10print(node1.next.data) # 20
24. 二叉树节点

题目:定义二叉树的节点类TreeNode,包含数据、左子节点和右子节点。

答案

class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = Noneroot = TreeNode(1)root.left = TreeNode(2)root.right = TreeNode(3)print(root.left.data) # 2
25. 字典统计

题目:统计字符串\"abracadabra\"中每个字符的出现次数。

答案

s = \"abracadabra\"count_dict = { }for char in s: count_dict[char] = count_dict.get(char, 0) + 1print(count_dict) # {\'a\': 5, \'b\': 2, \'r\': 2, \'c\': 1, \'d\': 1}
26. 列表去重

题目:去除列表[1, 2, 2, 3, 3, 3]中的重复元素。

答案

my_list = [1, 2, 2, 3, 3, 3]unique_list = list(set(my_list))print(unique_list) # [1, 2, 3]
27. 二维列表

题目:创建一个3x3的二维列表,每个元素为其行列索引的和。

答案

matrix = [[i+j for j in range(3)] for i in range(3)]print(matrix) # [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
28. 字典排序

题目:根据字典的值对字典{\"a\": 3, \"b\": 1, \"c\": 2}进行升序排序。

答案

my_dict = { \"a\": 3, \"b\": 1, \"c\": 2}sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))print(sorted_dict) # {\'b\': 1, \'c\': 2, \'a\': 3}
29. 堆排序

题目:使用Python内置的heapq模块实现堆排序。

答案

import heapqdef heap_sort(arr): h = [] for value in arr: heapq.heappush(h, value) return [heapq.heappop(h) for _ in range(len(h))]arr = [3, 1, 4, 1, 5, 9]print(heap_sort(arr)) # [1, 1, 3, 4, 5, 9]
30. 冒泡排序

题目:实现冒泡排序算法。

答案

def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arrarr = [3, 1, 4, 1, 5, 9]print(bubble_sort(arr)) # [1, 1, 3, 4, 5, 9]
31. 快速排序

题目:实现快速排序算法。

答案

def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] left = [x for x in arr[1:] if x <= pivot] right = [x for x in arr[1:] if x > pivot] return quick_sort(left) + [pivot] + quick_sort(right)arr = [3, 1, 4, 1, 5, 9]print(quick_sort(arr)) # [1, 1, 3, 4, 5, 9]
32. 二分查找

题目:在有序列表[1, 3, 5, 7, 9]中查找元素5的索引。

答案

def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1arr = [1, 3, 5, 7, 9]print(binary_search(arr, 5)) # 2
33. 斐波那契数列

题目:生成前10个斐波那契数列。

答案

def fibonacci(n): fibs = [0, 1] for i in range(2, n): fibs.append(fibs[-1] + fibs[-2]) return fibs[:n]print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
34. 矩阵转置

题目:将矩阵[[1, 2], [3, 4], [5, 6]]转置。

答案

matrix = [[1, 2], [3, 4], [5, 6]]transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]print(transposed) # [[1, 3, 5], [2, 4, 6]]
35. 反转链表

题目:反转链表1->2->33->2->1

答案

class Node: def __init__(self, data): self.data = data self.next = None# 创建链表 1->2->3head = Node(1)head.next = Node(2)head.next.next = Node(3)# 反转链表prev = Nonecurrent = headwhile current: next_node = current.next current.next = prev prev = current current = next_node# 打印反转后的链表node = prevwhile node: print(node.data, end=\"->\") # 3->2->1-> node = node.next
36. 集合运算

题目:给定集合A = {1, 2, 3}B = {3, 4, 5},求A-BB-AA⊕B

答案

A = { 1, 2, 3}B = { 3, 4, 5}diff1 = A - B # {1, 2}diff2 = B - A # {4, 5}sym_diff = A ^ B # {1, 2, 4, 5}print(diff1, diff2, sym_diff)
37. 栈判断括号匹配

题目:使用栈判断字符串\"(()())\"中的括号是否匹配。

答案

def is_matched(s): stack = [] for char in s: if char == \'(\': stack.append(char) elif char == \')\': if not stack: return False stack.pop() return len(stack) == 0print(is_matched(\"(()())\")) # True
38. 字典合并

题目:合并两个字典d1 = {\"a\": 1}d2 = {\"b\": 2}

答案

d1 = { \"a\": 1}d2 = { \"b\": 2}merged = { **d1, **d2}print(merged) # {\'a\': 1, \'b\': 2}
39. 列表扁平化

题目:将嵌套列表[1, [2, [3, 4]]]展平为[1, 2, 3, 4]

答案

def flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(flatten(item)) else