跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
PythonAI算法

Python 入门 60 个基础练习:从零掌握核心语法

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

奶糖兔发布于 2026/3/27更新于 2026/10/24129 浏览
Python 入门 60 个基础练习:从零掌握核心语法

一、变量与数据类型(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 高级特性和应用领域的基础。

目录

  1. 一、变量与数据类型(1-10)
  2. 1. 变量赋值与输出
  3. 2. 数据类型转换
  4. 3. 数值计算
  5. 4. 字符串拼接
  6. 5. 布尔值与逻辑运算
  7. 6. 列表基本操作
  8. 7. 元组不可变性
  9. 8. 字典基本操作
  10. 9. 集合去重
  11. 10. 类型检查
  12. 二、字符串操作(11-20)
  13. 11. 字符串索引
  14. 12. 字符串切片
  15. 13. 字符串反转
  16. 14. 字符串大小写转换
  17. 15. 字符串替换
  18. 16. 字符串分割
  19. 17. 字符串连接
  20. 18. 字符串长度
  21. 19. 字符串查找
  22. 20. 字符串格式化
  23. 三、列表与元组(21-30)
  24. 21. 列表索引与切片
  25. 22. 列表修改
  26. 23. 列表追加元素
  27. 24. 列表插入元素
  28. 25. 列表删除元素
  29. 26. 列表排序
  30. 27. 列表反转
  31. 28. 列表长度
  32. 29. 列表最大值和最小值
  33. 30. 元组解包
  34. 四、字典与集合(31-40)
  35. 31. 字典基本操作
  36. 32. 字典获取值
  37. 33. 字典修改值
  38. 34. 字典删除键值对
  39. 35. 字典获取所有键
  40. 36. 字典获取所有值
  41. 37. 字典获取所有键值对
  42. 38. 字典长度
  43. 39. 集合添加元素
  44. 40. 集合并集
  45. 五、条件语句与循环(41-50)
  46. 41. if 语句
  47. 42. if-else 语句
  48. 43. if-elif-else 语句
  49. 44. for 循环遍历列表
  50. 45. for 循环与 range 函数
  51. 46. while 循环
  52. 47. break 语句
  53. 48. continue 语句
  54. 49. 嵌套循环
  55. 50. 循环中的 else 子句
  56. 六、函数与模块(51-60)
  57. 51. 定义简单函数
  58. 52. 函数参数默认值
  59. 53. 函数返回多个值
  60. 54. 匿名函数(lambda)
  61. 55. 模块导入
  62. 56. 从模块导入特定函数
  63. 57. 自定义模块
  64. calculator.py
  65. main.py
  66. 58. 文件读取
  67. 59. 文件写入
  68. 60. 异常处理
  69. 总结

更多推荐文章

查看全部
  • Python 接入天远劳动仲裁 API 构建企业风控体系
  • GitHub Copilot Pro 学生免费认证与 VS Code 集成指南
  • RVC-WebUI 语音转换工具部署与使用指南
  • Kimi K2.5 开源部署、API 接入、Agent 集群与多模态视觉实战
  • OpenClaw:打造你的本地 AI 数字管家
  • AIGC 情感化智能客服实战:降低投诉率的技术方案
  • C++20 概念(Concepts):模板参数的语义约束定义
  • C++ 继承机制核心解析
  • 对抗学习原理与代码实战详解
  • Java 模拟算法实战:LeetCode 经典题解
  • 双指针算法:四数之和解题思路与实现
  • w64devkit:Windows C/C++轻量级编译环境搭建指南
  • 算法练习:多重背包、贪心差分、DFS 及路径 DP 题解
  • Stable Diffusion 3.5 LoRA 微调指南
  • Copilot 接入第三方 OpenAI 接口配置方案
  • 基于 Python 的流处理与 RAG 驱动智能 ETL 框架设计
  • MiroFish:基于多智能体的群体智能预测引擎实战
  • OpenClaw 接入自定义模型及 WebUI 智能操作指南
  • Flet:用 Python 构建跨平台桌面与 Web 应用
  • Web SQL Database API:被时代淘汰的浏览器存储技术

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如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