跳到主要内容Python 入门 60 个基础练习:从零掌握核心语法 | 极客日志PythonAI算法
Python 入门 60 个基础练习:从零掌握核心语法
提供 60 个 Python 基础练习,涵盖变量类型、字符串操作、列表元组、字典集合、条件循环及函数模块等核心语法。每个练习包含题目、代码示例及知识点解析,适合零基础学习者系统掌握 Python 编程。
奶糖兔45 浏览 一、变量与数据类型(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)
知识点:
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 =
(result)
f"{greeting}, {target}!"
print
5. 布尔值与逻辑运算
result = 5 > 3 and 5 < 10
print(result)
- 布尔值(True/False)
- 逻辑运算符(and、or、not)
6. 列表基本操作
题目:创建列表 [1, 2, 3],添加元素 4,然后打印列表。
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
7. 元组不可变性
题目:创建元组 (1, 2, 3),尝试修改第一个元素为 10。
my_tuple = (1, 2, 3)
try:
my_tuple[0] = 10
except TypeError as e:
print(f"错误:{e}")
8. 字典基本操作
题目:创建字典 {'name': 'Alice', 'age': 25},添加键值对 'city': 'New York'。
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict)
9. 集合去重
题目:将列表 [1, 2, 2, 3, 3, 3] 转换为集合以去重。
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)
print(my_set)
10. 类型检查
二、字符串操作(11-20)
11. 字符串索引
题目:提取字符串 "Python" 的第 3 个字符(索引为 2)。
12. 字符串切片
题目:提取字符串 "Hello, World!" 的前 5 个字符。
s = "Hello, World!"
print(s[:5])
13. 字符串反转
s = "Python"
reversed_s = s[::-1]
print(reversed_s)
14. 字符串大小写转换
题目:将字符串 "python is fun" 转换为大写。
s = "python is fun"
print(s.upper())
15. 字符串替换
题目:将字符串 "Hello, World!" 中的 "World" 替换为 "Python"。
s = "Hello, World!"
new_s = s.replace("World", "Python")
print(new_s)
16. 字符串分割
题目:将字符串 "apple,banana,cherry" 按逗号分割为列表。
s = "apple,banana,cherry"
fruits = s.split(',')
print(fruits)
17. 字符串连接
题目:将列表 ['apple', 'banana', 'cherry'] 用连字符 - 连接成字符串。
fruits = ['apple', 'banana', 'cherry']
s = '-'.join(fruits)
print(s)
18. 字符串长度
题目:计算字符串 "Python Programming" 的长度。
s = "Python Programming"
print(len(s))
19. 字符串查找
题目:查找字符串 "Python Programming" 中 "Programming" 的起始索引。
s = "Python Programming"
index = s.find("Programming")
print(index)
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)
三、列表与元组(21-30)
21. 列表索引与切片
题目:创建列表 [1, 2, 3, 4, 5],提取前三个元素。
my_list = [1, 2, 3, 4, 5]
print(my_list[:3])
22. 列表修改
题目:将列表 [1, 2, 3, 4, 5] 的第三个元素修改为 30。
my_list = [1, 2, 3, 4, 5]
my_list[2] = 30
print(my_list)
23. 列表追加元素
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
24. 列表插入元素
题目:在列表 [1, 2, 4, 5] 的第三个位置插入元素 3。
my_list = [1, 2, 4, 5]
my_list.insert(2, 3)
print(my_list)
25. 列表删除元素
题目:删除列表 [1, 2, 3, 4, 5] 中的元素 3。
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)
26. 列表排序
题目:对列表 [5, 3, 1, 4, 2] 进行升序排序。
my_list = [5, 3, 1, 4, 2]
my_list.sort()
print(my_list)
27. 列表反转
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)
28. 列表长度
题目:计算列表 [1, 2, 3, 4, 5] 的长度。
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
29. 列表最大值和最小值
题目:找出列表 [5, 3, 1, 4, 2] 中的最大值和最小值。
my_list = [5, 3, 1, 4, 2]
print(max(my_list))
print(min(my_list))
30. 元组解包
题目:将元组 (1, 2, 3) 解包到变量 a, b, c 中。
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)
四、字典与集合(31-40)
31. 字典基本操作
题目:创建字典 {'name': 'Alice', 'age': 25},添加键值对 'city': 'New York'。
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict)
32. 字典获取值
题目:从字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 中获取 'age' 的值。
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict['age'])
33. 字典修改值
题目:将字典 {'name': 'Alice', 'age': 25} 中的 'age' 修改为 26。
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
print(my_dict)
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)
35. 字典获取所有键
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 的所有键。
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.keys())
36. 字典获取所有值
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 的所有值。
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.values())
37. 字典获取所有键值对
题目:获取字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 的所有键值对。
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict.items())
38. 字典长度
题目:计算字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 的长度。
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(len(my_dict))
39. 集合添加元素
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
40. 集合并集
题目:计算集合 {1, 2, 3} 和 {3, 4, 5} 的并集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1.union(set2)
print(union)
五、条件语句与循环(41-50)
41. if 语句
题目:判断变量 x = 10 是否大于 5,如果是则打印 'x 大于 5'。
x = 10
if x > 5:
print("x 大于 5")
42. if-else 语句
题目:判断变量 x = 3 是否大于 5,如果是则打印 'x 大于 5',否则打印 'x 小于等于 5'。
x = 3
if x > 5:
print("x 大于 5")
else:
print("x 小于等于 5")
43. if-elif-else 语句
题目:判断变量 x = 0 的符号,如果是正数则打印 '正数',如果是负数则打印 '负数',否则打印 '零'。
x = 0
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
44. for 循环遍历列表
题目:使用 for 循环遍历列表 [1, 2, 3, 4, 5] 并打印每个元素。
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)
45. for 循环与 range 函数
题目:使用 for 循环和 range 函数打印 1 到 5 的数字。
for i in range(1, 6):
print(i)
46. while 循环
题目:使用 while 循环打印 1 到 5 的数字。
i = 1
while i <= 5:
print(i)
i += 1
47. break 语句
题目:使用 for 循环遍历 1 到 10 的数字,当遇到 5 时跳出循环。
for i in range(1, 11):
if i == 5:
break
print(i)
48. continue 语句
题目:使用 for 循环遍历 1 到 10 的数字,当遇到偶数时跳过当前循环。
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
49. 嵌套循环
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")
六、函数与模块(51-60)
51. 定义简单函数
题目:定义一个函数 add,接受两个参数并返回它们的和。
def add(a, b):
return a + b
result = add(3, 5)
print(result)
52. 函数参数默认值
题目:定义一个函数 greet,接受一个名字参数,默认值为 'World',返回问候语。
def greet(name="World"):
return f"Hello, {name}!"
print(greet())
print(greet("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}")
54. 匿名函数(lambda)
multiply = lambda a, b: a * b
print(multiply(3, 5))
55. 模块导入
import math
result = math.sqrt(16)
print(result)
56. 从模块导入特定函数
题目:从 math 模块导入 pi 常量和 sin 函数,计算 sin(π/2)。
from math import pi, sin
result = sin(pi / 2)
print(result)
57. 自定义模块
题目:创建一个名为 calculator.py 的模块,包含 add、subtract、multiply 和 divide 四个函数,然后在另一个文件中导入并使用这些函数。
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
from calculator import add, subtract, multiply, divide
print(add(3, 5))
print(subtract(8, 3))
print(multiply(4, 5))
print(divide(10, 2))
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))
print(divide(10, 0))
print(divide("10", 2))
总结
通过这 60 个基础练习,你已经掌握了 Python 编程的核心语法,包括变量、数据类型、字符串操作、列表与元组、字典与集合、条件语句、循环结构、函数定义和模块导入等。这些知识是进一步学习 Python 高级特性和应用领域的基础。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online