Python 作为一门简单易学、功能强大的编程语言,已成为数据科学、人工智能、Web 开发等领域的首选语言。本文精心设计了60个基础练习,涵盖 Python 语法的各个方面,帮助零基础学习者逐步掌握 Python 编程的核心概念。通过这些练习,你将系统性地学习变量、数据类型、控制结构、函数、模块等基础知识,并通过实际案例加深理解。
一、变量与数据类型(1-10)
1. 变量赋值与输出
题目:创建变量 name
存储你的姓名,age
存储你的年龄,然后打印 “你好,我是[姓名],今年[年龄]岁。”
答案:
name = "张三"
age = 25
print(f"你好,我是{name},今年{age}岁。")
知识点:
- 变量命名规则(只能包含字母、数字、下划线,且不能以数字开头)
- 字符串格式化(f-string 方法)
2. 数据类型转换
题目:将字符串 “123” 转换为整数,将整数 3 转换为浮点数,然后计算它们的和。
答案:
a = int("123")
b = float(3)
result = a + b
print(result) # 输出126.0
知识点:
int()
、float()
、str()
类型转换函数- 数据类型的隐式转换规则
3. 数值计算
题目:计算圆的面积,半径为 5(π 取 3.14)。
答案:
radius = 5
area = 3.14 * radius ** 2
print(f"圆的面积是:{area}")
知识点:
- 算术运算符(
+
、-
、*
、/
、**
、%
) - 运算优先级规则
4. 字符串拼接
题目:将字符串 “Hello” 和 “World” 拼接成 “Hello, World!”。
答案:
greeting = "Hello"
target = "World"
result = f"{greeting}, {target}!"
print(result)
知识点:
- 字符串拼接的多种方式(
+
、f-string)
5. 布尔值与逻辑运算
题目:判断 5 是否大于 3 且小于 10。
答案:
result = 5 > 3 and 5 < 10
print(result) # 输出 True
知识点:
- 布尔值(True/False)
- 逻辑运算符(and、or、not)
6. 列表基本操作
题目:创建列表 [1, 2, 3]
,添加元素 4,然后打印列表。
答案:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出 [1, 2, 3, 4]
知识点:
- 列表的可变性
append()
方法添加元素
7. 元组不可变性
题目:创建元组 (1, 2, 3)
,尝试修改第一个元素为 10。
答案:
my_tuple = (1, 2, 3)
try:
my_tuple[0] = 10 # 这行会报错
except TypeError as e:
print(f"错误:{e}")
知识点:
- 元组的不可变性
- 异常处理(try-except)
8. 字典基本操作
题目:创建字典 {'name': 'Alice', 'age': 25}
,添加键值对 'city': 'New York'
。
答案:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict) # 输出 {'name': 'Alice', 'age': 25, 'city': 'New York'}
知识点:
- 字典的键值对结构
- 动态添加键值对
9. 集合去重
题目:将列表 [1, 2, 2, 3, 3, 3]
转换为集合以去重。
答案:
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)
print(my_set) # 输出 {1, 2, 3}
知识点:
- 集合的元素唯一性
- 列表与集合的转换
10. 类型检查
题目:检查变量 x = 10
的数据类型。
答案:
x = 10
print(type(x)) # 输出 <class 'int'>
知识点:
type()
函数- Python 的动态类型特性
二、字符串操作(11-20)
11. 字符串索引
题目:提取字符串 "Python"
的第 3 个字符(索引为 2)。
答案:
s = "Python"
print(s[2]) # 输出 't'
知识点:
- 字符串索引(从 0 开始)
12. 字符串切片
题目:提取字符串 "Hello, World!"
的前 5 个字符。
答案:
s = "Hello, World!"
print(s[:5]) # 输出 'Hello'
知识点:
- 切片语法
[start:end]
13. 字符串反转
题目:反转字符串 "Python"
。
答案:
s = "Python"
reversed_s = s[::-1]
print(reversed_s) # 输出 'nohtyP'
知识点:
- 切片步长为负数的用法
14. 字符串大小写转换
题目:将字符串 "python is fun"
转换为大写。
答案:
s = "python is fun"
print(s.upper()) # 输出 'PYTHON IS FUN'
知识点:
upper()
和lower()
方法
15. 字符串替换
题目:将字符串 "Hello, World!"
中的 "World"
替换为 "Python"
。
答案:
s = "Hello, World!"
new_s = s.replace("World", "Python")
print(new_s) # 输出 'Hello, Python!'
知识点:
replace()
方法的使用
16. 字符串分割
题目:将字符串 "apple,banana,cherry"
按逗号分割为列表。
答案:
s = "apple,banana,cherry"
fruits = s.split(',')
print(fruits) # 输出 ['apple', 'banana', 'cherry']
知识点:
split()
方法的使用
17. 字符串连接
题目:将列表 ['apple', 'banana', 'cherry']
用连字符 -
连接成字符串。
答案:
fruits = ['apple', 'banana', 'cherry']
s = '-'.join(fruits)
print(s) # 输出 'apple-banana-cherry'
知识点:
join()
方法的使用
18. 字符串长度
题目:计算字符串 "Python Programming"
的长度。
答案:
s = "Python Programming"
print(len(s)) # 输出 18
知识点:
len()
函数的使用
19. 字符串查找
题目:查找字符串 "Python Programming"
中 "Programming"
的起始索引。
答案:
s = "Python Programming"
index = s.find("Programming")
print(index) # 输出 7
知识点:
find()
方法的使用
20. 字符串格式化
题目:使用格式化方法将变量 name = "Alice"
和 age = 25
插入到字符串 "My name is {} and I am {} years old."
中。
答案:
name = "Alice"
age = 25
s = "My name is {} and I am {} years old.".format(name, age)
print(s) # 输出 'My name is Alice and I am 25 years old.'
知识点:
format()
方法的使用
三、列表与元组(21-30)
21. 列表索引与切片
题目:创建列表 [1, 2, 3, 4, 5]
,提取前三个元素。
答案:
my_list = [1, 2, 3, 4, 5]
print(my_list[:3]) # 输出 [1, 2, 3]
知识点:
- 列表切片操作
22. 列表修改
题目:将列表 [1, 2, 3, 4, 5]
的第三个元素修改为 30。
答案:
my_list = [1, 2, 3, 4, 5]
my_list[2] = 30
print(my_list) # 输出 [1, 2, 30, 4, 5]
知识点:
- 列表的可变性
23. 列表追加元素
题目:向列表 [1, 2, 3]
追加元素 4。
答案:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出 [1, 2, 3, 4]
知识点:
append()
方法的使用
24. 列表插入元素
题目:在列表 [1, 2, 4, 5]
的第三个位置插入元素 3。
答案:
my_list = [1, 2, 4, 5]
my_list.insert(2, 3)
print(my_list) # 输出 [1, 2, 3, 4, 5]
知识点:
insert()
方法的使用
25. 列表删除元素
题目:删除列表 [1, 2, 3, 4, 5]
中的元素 3。
答案:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # 输出 [1, 2, 4, 5]
知识点:
remove()
方法的使用
26. 列表排序
题目:对列表 [5, 3, 1, 4, 2]
进行升序排序。
答案:
my_list = [5, 3, 1, 4, 2]
my_list.sort()
print(my_list) # 输出 [1, 2, 3, 4, 5]
知识点:
sort()
方法的使用
27. 列表反转
题目:反转列表 [1, 2, 3, 4, 5]
。
答案:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # 输出 [5, 4, 3, 2, 1]
知识点:
reverse()
方法的使用
28. 列表长度
题目:计算列表 [1, 2, 3, 4, 5]
的长度。
答案:
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 输出 5
知识点:
len()
函数的使用
29. 列表最大值和最小值
题目:找出列表 [5, 3, 1, 4, 2]
中的最大值和最小值。
答案:
my_list = [5, 3, 1, 4, 2]
print(max(my_list)) # 输出 5
print(min(my_list)) # 输出 1
知识点:
max()
和min()
函数的使用
30. 元组解包
题目:将元组 (1, 2, 3)
解包到变量 a
, b
, c
中。
答案:
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # 输出 1 2 3
知识点:
- 元组解包的语法
四、字典与集合(31-40)
31. 字典基本操作
题目:创建字典 {'name': 'Alice', 'age': 25}
,添加键值对 'city': 'New York'
。
答案:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict) # 输出 {'name': 'Alice', 'age': 25, 'city': 'New York'}
知识点:
- 字典的动态添加键值对
32. 字典获取值
题目:从字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
中获取 'age'
的值。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict['age']) # 输出 25
知识点:
- 通过键获取字典的值
33. 字典修改值
题目:将字典 {'name': 'Alice', 'age': 25}
中的 'age'
修改为 26。
答案:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
print(my_dict) # 输出 {'name': 'Alice', 'age': 26}
知识点:
- 字典值的修改
34. 字典删除键值对
题目:删除字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
中的 'city'
键值对。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
del my_dict['city']
print(my_dict) # 输出 {'name': 'Alice', 'age': 25}
知识点:
del
语句删除字典键值对
35. 字典获取所有键
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
的所有键。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.keys()) # 输出 dict_keys(['name', 'age', 'city'])
知识点:
keys()
方法获取字典所有键
36. 字典获取所有值
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
的所有值。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.values()) # 输出 dict_values(['Alice', 25, 'New York'])
知识点:
values()
方法获取字典所有值
37. 字典获取所有键值对
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
的所有键值对。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.items()) # 输出 dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
知识点:
items()
方法获取字典所有键值对
38. 字典长度
题目:计算字典 {'name': 'Alice', 'age': 25, 'city': 'New York'}
的长度。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(len(my_dict)) # 输出 3
知识点:
len()
函数计算字典长度
39. 集合添加元素
题目:向集合 {1, 2, 3}
添加元素 4。
答案:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出 {1, 2, 3, 4}
知识点:
add()
方法添加集合元素
40. 集合并集
题目:计算集合 {1, 2, 3}
和 {3, 4, 5}
的并集。
答案:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1.union(set2)
print(union) # 输出 {1, 2, 3, 4, 5}
知识点:
union()
方法计算集合并集
五、条件语句与循环(41-50)
41. if语句
题目:判断变量 x = 10
是否大于 5,如果是则打印 “x大于5”。
答案:
x = 10
if x > 5:
print("x大于5")
知识点:
if
语句的基本结构
42. if-else语句
题目:判断变量 x = 3
是否大于 5,如果是则打印 “x大于5”,否则打印 “x小于等于5”。
答案:
x = 3
if x > 5:
print("x大于5")
else:
print("x小于等于5")
知识点:
if-else
语句的基本结构
43. if-elif-else语句
题目:判断变量 x = 0
的符号,如果是正数则打印 “正数”,如果是负数则打印 “负数”,否则打印 “零”。
答案:
x = 0
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
知识点:
if-elif-else
语句的基本结构
44. for循环遍历列表
题目:使用for循环遍历列表 [1, 2, 3, 4, 5]
并打印每个元素。
答案:
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)
知识点:
for
循环遍历列表
45. for循环与range函数
题目:使用for循环和range函数打印1到5的数字。
答案:
for i in range(1, 6):
print(i)
知识点:
range()
函数的使用
46. while循环
题目:使用while循环打印1到5的数字。
答案:
i = 1
while i <= 5:
print(i)
i += 1
知识点:
while
循环的基本结构
47. break语句
题目:使用for循环遍历1到10的数字,当遇到5时跳出循环。
答案:
for i in range(1, 11):
if i == 5:
break
print(i)
知识点:
break
语句跳出循环
48. continue语句
题目:使用for循环遍历1到10的数字,当遇到偶数时跳过当前循环。
答案:
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
知识点:
continue
语句跳过当前循环
49. 嵌套循环
题目:使用嵌套for循环打印九九乘法表。
答案:
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()
知识点:
- 嵌套循环的使用
50. 循环中的else子句
题目:使用for循环遍历列表 [1, 2, 3, 4, 5]
,如果列表中没有元素6,则打印 “列表中没有元素6”。
答案:
my_list = [1, 2, 3, 4, 5]
for num in my_list:
if num == 6:
break
else:
print("列表中没有元素6")
知识点:
- 循环中的
else
子句
六、函数与模块(51-60)
51. 定义简单函数
题目:定义一个函数 add
,接受两个参数并返回它们的和。
答案:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出 8
知识点:
- 函数的定义与调用
52. 函数参数默认值
题目:定义一个函数 greet
,接受一个名字参数,默认值为 “World”,返回问候语。
答案:
def greet(name="World"):
return f"Hello, {name}!"
print(greet()) # 输出 "Hello, World!"
print(greet("Alice")) # 输出 "Hello, Alice!"
知识点:
- 函数参数的默认值
53. 函数返回多个值
题目:定义一个函数 get_name_and_age
,返回名字和年龄两个值。
答案:
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}") # 输出 "Name: Alice, Age: 25"
知识点:
- 函数返回多个值(元组解包)
54. 匿名函数(lambda)
题目:使用lambda函数计算两个数的乘积。
答案:
multiply = lambda a, b: a * b
print(multiply(3, 5)) # 输出 15
知识点:
- lambda函数的定义与使用
55. 模块导入
题目:导入 math
模块,计算根号16。
答案:
import math
result = math.sqrt(16)
print(result) # 输出 4.0
知识点:
- 模块的导入与使用
56. 从模块导入特定函数
题目:从 math
模块导入 pi
常量和 sin
函数,计算sin(π/2)。
答案:
from math import pi, sin
result = sin(pi / 2)
print(result) # 输出 1.0
知识点:
- 从模块导入特定函数或常量
57. 自定义模块
题目:创建一个名为 calculator.py
的模块,包含 add
、subtract
、multiply
和 divide
四个函数,然后在另一个文件中导入并使用这些函数。
答案:
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
# main.py
from calculator import add, subtract, multiply, divide
print(add(3, 5)) # 输出 8
print(subtract(8, 3)) # 输出 5
print(multiply(4, 5)) # 输出 20
print(divide(10, 2)) # 输出 5.0
知识点:
- 自定义模块的创建与使用
58. 文件读取
题目:读取文件 example.txt
的内容并打印。
答案:
try:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件不存在")
知识点:
- 文件读取的基本方法
59. 文件写入
题目:将字符串 “Hello, World!” 写入文件 output.txt
。
答案:
with open('output.txt', 'w') as file:
file.write("Hello, World!")
知识点:
- 文件写入的基本方法
60. 异常处理
题目:编写一个函数 divide
,接受两个参数,计算它们的商,并处理可能的除零错误和类型错误。
答案:
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("错误:除数不能为零")
except TypeError:
print("错误:参数必须是数字")
print(divide(10, 2)) # 输出 5.0
print(divide(10, 0)) # 输出 "错误:除数不能为零"
print(divide("10", 2)) # 输出 "错误:参数必须是数字"
知识点:
- 异常处理的基本方法
总结
通过这60个基础练习,你已经掌握了 Python 编程的核心语法,包括变量、数据类型、字符串操作、列表与元组、字典与集合、条件语句、循环结构、函数定义和模块导入等。这些知识是进一步学习 Python 高级特性和应用领域的基础。
建议你在完成练习后,尝试编写一些综合性的小项目,如简单的计算器、学生成绩管理系统或数据处理脚本,以巩固所学知识。持续实践和不断探索是成为优秀程序员的关键!