Python 入门 60 个基础练习:从零掌握核心语法
提供 60 个 Python 基础练习,涵盖变量类型、字符串操作、列表元组、字典集合、条件循环及函数模块等核心语法。每个练习包含题目、代码示例及知识点解析,适合零基础学习者系统掌握 Python 编程。

提供 60 个 Python 基础练习,涵盖变量类型、字符串操作、列表元组、字典集合、条件循环及函数模块等核心语法。每个练习包含题目、代码示例及知识点解析,适合零基础学习者系统掌握 Python 编程。

题目:创建变量 name 存储你的姓名,age 存储你的年龄,然后打印 '你好,我是 [姓名],今年 [年龄] 岁。'
答案:
name = "张三"
age = 25
print(f"你好,我是{name},今年{age}岁。")
知识点:
题目:将字符串 '123' 转换为整数,将整数 3 转换为浮点数,然后计算它们的和。
答案:
a = int("123")
b = float(3)
result = a + b
print(result) # 输出 126.0
知识点:
int()、float()、str() 类型转换函数题目:计算圆的面积,半径为 5(π 取 3.14)。
答案:
radius = 5
area = 3.14 * radius ** 2
print(f"圆的面积是:{area}")
知识点:
+、-、*、/、**、%)题目:将字符串 'Hello' 和 'World' 拼接成 'Hello, World!'。
答案:
greeting = "Hello"
target = "World"
result = f"{greeting}, {target}!"
print(result)
知识点:
+、f-string)题目:判断 5 是否大于 3 且小于 10。
答案:
result = 5 > 3 and 5 < 10
print(result) # 输出 True
知识点:
题目:创建列表 [1, 2, 3],添加元素 4,然后打印列表。
答案:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出 [1, 2, 3, 4]
知识点:
append() 方法添加元素题目:创建元组 (1, 2, 3),尝试修改第一个元素为 10。
答案:
my_tuple = (1, 2, 3)
try:
my_tuple[0] = 10 # 这行会报错
except TypeError as e:
print(f"错误:{e}")
知识点:
题目:创建字典 {'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'}
知识点:
题目:将列表 [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}
知识点:
题目:检查变量 x = 10 的数据类型。
答案:
x = 10
print(type(x)) # 输出 <class 'int'>
知识点:
type() 函数题目:提取字符串 "Python" 的第 3 个字符(索引为 2)。
答案:
s = "Python"
print(s[2]) # 输出 't'
知识点:
题目:提取字符串 "Hello, World!" 的前 5 个字符。
答案:
s = "Hello, World!"
print(s[:5]) # 输出 'Hello'
知识点:
[start:end]题目:反转字符串 "Python"。
答案:
s = "Python"
reversed_s = s[::-1]
print(reversed_s) # 输出 'nohtyP'
知识点:
题目:将字符串 "python is fun" 转换为大写。
答案:
s = "python is fun"
print(s.upper()) # 输出 'PYTHON IS FUN'
知识点:
upper() 和 lower() 方法题目:将字符串 "Hello, World!" 中的 "World" 替换为 "Python"。
答案:
s = "Hello, World!"
new_s = s.replace("World", "Python")
print(new_s) # 输出 'Hello, Python!'
知识点:
replace() 方法的使用题目:将字符串 "apple,banana,cherry" 按逗号分割为列表。
答案:
s = "apple,banana,cherry"
fruits = s.split(',')
print(fruits) # 输出 ['apple', 'banana', 'cherry']
知识点:
split() 方法的使用题目:将列表 ['apple', 'banana', 'cherry'] 用连字符 - 连接成字符串。
答案:
fruits = ['apple', 'banana', 'cherry']
s = '-'.join(fruits)
print(s) # 输出 'apple-banana-cherry'
知识点:
join() 方法的使用题目:计算字符串 "Python Programming" 的长度。
答案:
s = "Python Programming"
print(len(s)) # 输出 18
知识点:
len() 函数的使用题目:查找字符串 "Python Programming" 中 "Programming" 的起始索引。
答案:
s = "Python Programming"
index = s.find("Programming")
print(index) # 输出 7
知识点:
find() 方法的使用题目:使用格式化方法将变量 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() 方法的使用题目:创建列表 [1, 2, 3, 4, 5],提取前三个元素。
答案:
my_list = [1, 2, 3, 4, 5]
print(my_list[:3]) # 输出 [1, 2, 3]
知识点:
题目:将列表 [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]
知识点:
题目:向列表 [1, 2, 3] 追加元素 4。
答案:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出 [1, 2, 3, 4]
知识点:
append() 方法的使用题目:在列表 [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() 方法的使用题目:删除列表 [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() 方法的使用题目:对列表 [5, 3, 1, 4, 2] 进行升序排序。
答案:
my_list = [5, 3, 1, 4, 2]
my_list.sort()
print(my_list) # 输出 [1, 2, 3, 4, 5]
知识点:
sort() 方法的使用题目:反转列表 [1, 2, 3, 4, 5]。
答案:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # 输出 [5, 4, 3, 2, 1]
知识点:
reverse() 方法的使用题目:计算列表 [1, 2, 3, 4, 5] 的长度。
答案:
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 输出 5
知识点:
len() 函数的使用题目:找出列表 [5, 3, 1, 4, 2] 中的最大值和最小值。
答案:
my_list = [5, 3, 1, 4, 2]
print(max(my_list)) # 输出 5
print(min(my_list)) # 输出 1
知识点:
max() 和 min() 函数的使用题目:将元组 (1, 2, 3) 解包到变量 a, b, c 中。
答案:
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # 输出 1 2 3
知识点:
题目:创建字典 {'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'}
知识点:
题目:从字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 中获取 'age' 的值。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict['age']) # 输出 25
知识点:
题目:将字典 {'name': 'Alice', 'age': 25} 中的 'age' 修改为 26。
答案:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
print(my_dict) # 输出 {'name': 'Alice', 'age': 26}
知识点:
题目:删除字典 {'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 语句删除字典键值对题目:获取字典 {'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() 方法获取字典所有键题目:获取字典 {'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() 方法获取字典所有值题目:获取字典 {'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() 方法获取字典所有键值对题目:计算字典 {'name': 'Alice', 'age': 25, 'city': 'New York'} 的长度。
答案:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(len(my_dict)) # 输出 3
知识点:
len() 函数计算字典长度题目:向集合 {1, 2, 3} 添加元素 4。
答案:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出 {1, 2, 3, 4}
知识点:
add() 方法添加集合元素题目:计算集合 {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() 方法计算集合并集题目:判断变量 x = 10 是否大于 5,如果是则打印 'x 大于 5'。
答案:
x = 10
if x > 5:
print("x 大于 5")
知识点:
if 语句的基本结构题目:判断变量 x = 3 是否大于 5,如果是则打印 'x 大于 5',否则打印 'x 小于等于 5'。
答案:
x = 3
if x > 5:
print("x 大于 5")
else:
print("x 小于等于 5")
知识点:
if-else 语句的基本结构题目:判断变量 x = 0 的符号,如果是正数则打印 '正数',如果是负数则打印 '负数',否则打印 '零'。
答案:
x = 0
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
知识点:
if-elif-else 语句的基本结构题目:使用 for 循环遍历列表 [1, 2, 3, 4, 5] 并打印每个元素。
答案:
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)
知识点:
for 循环遍历列表题目:使用 for 循环和 range 函数打印 1 到 5 的数字。
答案:
for i in range(1, 6):
print(i)
知识点:
range() 函数的使用题目:使用 while 循环打印 1 到 5 的数字。
答案:
i = 1
while i <= 5:
print(i)
i += 1
知识点:
while 循环的基本结构题目:使用 for 循环遍历 1 到 10 的数字,当遇到 5 时跳出循环。
答案:
for i in range(1, 11):
if i == 5:
break
print(i)
知识点:
break 语句跳出循环题目:使用 for 循环遍历 1 到 10 的数字,当遇到偶数时跳过当前循环。
答案:
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
知识点:
continue 语句跳过当前循环题目:使用嵌套 for 循环打印九九乘法表。
答案:
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()
知识点:
题目:使用 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 子句题目:定义一个函数 add,接受两个参数并返回它们的和。
答案:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出 8
知识点:
题目:定义一个函数 greet,接受一个名字参数,默认值为 'World',返回问候语。
答案:
def greet(name="World"):
return f"Hello, {name}!"
print(greet()) # 输出 "Hello, World!"
print(greet("Alice")) # 输出 "Hello, Alice!"
知识点:
题目:定义一个函数 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"
知识点:
题目:使用 lambda 函数计算两个数的乘积。
答案:
multiply = lambda a, b: a * b
print(multiply(3, 5)) # 输出 15
知识点:
题目:导入 math 模块,计算根号 16。
答案:
import math
result = math.sqrt(16)
print(result) # 输出 4.0
知识点:
题目:从 math 模块导入 pi 常量和 sin 函数,计算 sin(π/2)。
答案:
from math import pi, sin
result = sin(pi / 2)
print(result) # 输出 1.0
知识点:
题目:创建一个名为 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
知识点:
题目:读取文件 example.txt 的内容并打印。
答案:
try:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件不存在")
知识点:
题目:将字符串 'Hello, World!' 写入文件 output.txt。
答案:
with open('output.txt', 'w') as file:
file.write("Hello, World!")
知识点:
题目:编写一个函数 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 高级特性和应用领域的基础。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online