python 课后练习题

📋 50道Python基础课课后练习题

  1. 输入某年某月某日,判断这一天是这一年的第几天?
  2. 输入三个整数x,y,z,请把这三个数由小到大输出。
  3. 斐波那契数列(Fibonacci sequence),从1,1开始,后面每一项等于前面两项之和
  4. 将一个列表的数据复制到另一个列表中。
  5. 输出 9*9 乘法口诀表。
  6. 判断101-200之间有多少个素数,并输出所有素数
  7. 将一个整数分解质因数。例如:输入90,打印出90=233*5。
  8. 利用条件运算符的嵌套:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
  9. 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
  10. 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
  11. 求1+2!+3!+…+20!的和。
  12. 利用递归方法求5!。
  13. 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
  14. 给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
  15. 一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
  16. 按逗号分隔列表。
  17. 练习函数调用。
  18. 对10个数进行排序。
  19. 求一个3*3矩阵主对角线元素之和。
  20. 有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
  21. 将一个数组逆序输出。
  22. 模仿静态变量的用法。
  23. 学习使用auto定义变量的用法。
  24. 计算两个矩阵相加。
  25. 统计1到100之和。
  26. 求输入数字的平方,如果平方运算后小于50则退出。
  27. 两个变量值用函数互换。
  28. 数字比较。
  29. 使用lambda来创建匿名函数。
  30. 输出一个随机数。
  31. 学习使用按位与 &。
  32. 学习使用按位或 |。
  33. 学习使用按位异或 ^。
  34. 取一个整数a从右端开始的4〜7位。
  35. 学习使用按位取反~。
  36. 画图,学用circle画圆形。
  37. 画图,学用line画直线。
  38. 画图,学用rectangle画方形。
  39. 计算字符串长度。
  40. 打印出杨辉三角形前十行。
  41. 查找字符串。
  42. 输入3个数a,b,c,按大小顺序输出。
  43. 输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
  44. 写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。
  45. 编写input()和output()函数输入,输出5个学生的数据记录。
  46. 列表排序及连接。
  47. 编写一个函数,输入n为偶数时,调用函数求1/2+1/4+…+1/n,当输入n为奇数时,调用函数1/1+1/3+…+1/n
  48. 连接字符串。
  49. 输入一个奇数,然后判断最少几个9除于该数的结果为整数。
  50. 列表转换为字典。

🚀 50道Python高级课课后练习题

  1. 请解释Python中的全局解释器锁(GIL)以及它的作用。
  2. 请简要描述Python的垃圾收集机制。
  3. 请解释Python中的装饰器,并提供一个示例。
  4. 请解释Python中的生成器以及它们的用途。
  5. Python中*args和**kwargs的作用是什么?
  6. Python中的深拷贝和浅拷贝有什么区别?
  7. 请解释Python的异常处理以及如何使用try,except,finally和raise。
  8. 什么是Python中的上下文管理器?请提供一个实际用例。
  9. 如何在Python中创建一个单例类?
  10. Python中的元类是什么?它们有什么作用?
  11. 请解释Python中的列表推导式,并提供一个示例。
  12. Python中的闭包是什么?请提供一个示例。
  13. 请解释Python中的多态。
  14. Python中的协程是什么?它们的优势在哪里?
  15. 请解释Python的__name__属性的作用。
  16. 什么是Python的__init__.py文件的作用?
  17. 请解释Python中的命名空间。
  18. 请解释Python中的模块和包。
  19. Python中的迭代器和可迭代对象有什么区别?
  20. Python中的lambda函数有什么用?请提供一个示例。
  21. 请解释Python中的map(),filter()和reduce()函数的作用。
  22. 如何在Python中实现多线程?
  23. 请解释Python中的进程和线程的区别。
  24. Python中的asyncio库有什么作用?
  25. 请解释Python中的函数注解,并提供一个示例。
  26. Python中的类型提示是什么?它们有什么作用?
  27. 如何在Python中创建一个虚拟环境?
  28. 请解释Python中的pip工具的作用。
  29. 什么是Python中的requirements.txt文件?它有什么作用?
  30. 请解释Python中的__slots__属性的作用。
  31. Python中的staticmethod和classmethod有什么区别?
  32. 什么是Python中的迭代器协议?
  33. 请解释Python中的鸭子类型。
  34. Python中的super()函数有什么作用?
  35. 如何在Python中实现方法重载?
  36. Python中的@property装饰器有什么作用?
  37. 什么是Python中的递归?请提供一个示例。
  38. 请解释Python中的条件表达式,并提供一个示例。
  39. 如何在Python中计算一个字符串中的子字符串出现的次数?
  40. 如何在Python中将一个列表转换为字符串?
  41. 请解释Python中的内置函数enumerate()的作用。
  42. 如何在Python中创建一个不可变集合?
  43. Python中的zip()函数有什么作用?
  44. 在Python中,如何实现一个类的深度优先遍历?
  45. 如何在Python中实现一个简单的计时器装饰器?
  46. 请解释Python中的functools.wraps装饰器的作用。
  47. 如何在Python中实现一个简单的LRU缓存?
  48. 请解释Python中的os和sys模块的主要功能
  49. 在Python中,如何实现一个简单的HTTP服务器?
  50. 正则表达式的贪婪模式和非贪婪模式

🔍 50道其他问题_查漏补缺

1. filter函数筛选元素

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

result = filter(lambda x: x % 2 == 0, lst)
print(list(result))  # 输出 [2, 4, 6, 8]

2. reduce函数累加操作

from functools import reduce

lst = [1, 2, 3, 4, 5]

result = reduce(lambda x, y: x + y, lst)
print(result)  # 输出 15

3. map函数操作列表

lst = [1, 2, 3, 4, 5]

result = map(lambda x: x * 2, lst)
print(list(result))  # 输出 [2, 4, 6, 8, 10]

4. any函数判断

lst = [False, False, True, False]

result = any(lst)
print(result)  # 输出 True

5. all函数判断

lst = [True, True, False, True]

result = all(lst)
print(result)  # 输出 False

6. 闭包示例

def add(x):
    def inner(y):
        return x + y
    return inner

add_42 = add(42)
print(add_42(10))  # 输出 52

7. 浅拷贝和深拷贝

import copy

lst1 = [1, 2, 3, [4, 5]]
lst2 = copy.copy(lst1)      # 浅拷贝
lst3 = copy.deepcopy(lst1)  # 深拷贝

lst1[3].append(6)

print(lst1)  # [1, 2, 3, [4, 5, 6]]
print(lst2)  # [1, 2, 3, [4, 5, 6]] - 浅拷贝共享可变对象
print(lst3)  # [1, 2, 3, [4, 5]] - 深拷贝独立副本

8. 全局变量修改

x = 42  # 定义全局变量

def my_function():
    global x  # 声明x为全局变量
    x = 99    # 修改全局变量

my_function()
print(x)  # 输出 99

9. 模块导入

import math
import numpy as np
from collections import Counter

print(math.sqrt(2))
print(np.array([1, 2, 3]))
print(Counter([1, 2, 3, 2, 1]))

10. zip函数

lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
lst3 = [True, False, True]

result = list(zip(lst1, lst2, lst3))
print(result)  # [(1, 'a', True), (2, 'b', False), (3, 'c', True)]

11. 迭代器遍历

lst = [1, 2, 3]

it = iter(lst)
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

12. 字符串方法

s = "hello world"

print(s.upper())              # "HELLO WORLD"
print(s.lower())              # "hello world"
print(s.replace("world", "python"))  # "hello python"

13. datetime模块

import datetime

dt1 = datetime.datetime(2023, 6, 22, 8, 30, 0)
dt2 = datetime.datetime.now()

print(dt1)
print(dt2)
print(dt2 - dt1)

14. calendar模块

import calendar

cal = calendar.month(2023, 6)
print(cal)

15. numpy多维数组

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr)

16. 多线程

import threading

def my_function():
    print("Thread started")
    print("Thread finished")

t = threading.Thread(target=my_function)
t.start()

17. 多进程

import multiprocessing

def my_function():
    print("Process started")
    print("Process finished")

p = multiprocessing.Process(target=my_function)
p.start()

18. 文件操作

with open("file.txt", "r") as f:
    contents = f.read()
    print(contents)

with open("file.txt", "w") as f:
    f.write("Hello, world!")

19. SQLite操作

import sqlite3

conn = sqlite3.connect("mydb.sqlite")
c = conn.cursor()
c.execute("CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)")
c.execute("INSERT INTO mytable (name) VALUES ('Alice')")
conn.commit()

20. 枚举

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)
print(Color.RED.value)

21. 单例模式

class MySingleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

a = MySingleton()
b = MySingleton()
print(a is b)  # True

22. 工厂模式

class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("Drawing Circle")

class Square(Shape):
    def draw(self):
        print("Drawing Square")

class ShapeFactory:
    def create_shape(self, shape_type):
        if shape_type == "circle":
            return Circle()
        elif shape_type == "square":
            return Square()
        else:
            raise ValueError("Invalid shape type")

factory = ShapeFactory()
shape1 = factory.create_shape("circle")
shape1.draw()

23. 观察者模式

class Event:
    def __init__(self):
        self.handlers = []

    def add_handler(self, handler):
        self.handlers.append(handler)

    def notify(self, *args, **kwargs):
        for handler in self.handlers:
            handler(*args, **kwargs)

class Button:
    def __init__(self):
        self.clicked = Event()

    def click(self):
        self.clicked.notify()

def on_button_clicked():
    print("Button clicked")

button = Button()
button.clicked.add_handler(on_button_clicked)
button.click()

24. 生成器

def my_generator():
    yield 1
    yield 2
    yield 3

for x in my_generator():
    print(x)

25. 列表推导式

lst = [x**2 for x in range(10)]
print(lst)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

26. 集合运算

set1 = {1, 2, 3}
set2 = {2, 3, 4}

print(set1.union(set2))         # {1, 2, 3, 4}
print(set1.intersection(set2))  # {2, 3}
print(set1.difference(set2))    # {1}

27. 正则表达式

import re

s = "hello world"
pattern = r"o"

result = re.findall(pattern, s)
print(result)  # ['o', 'o']

28. pickle序列化

import pickle

data = {"x": 42, "y": [1, 2, 3]}
with open("data.pickle", "wb") as f:
    pickle.dump(data, f)

with open("data.pickle", "rb") as f:
    loaded_data = pickle.load(f)
    print(loaded_data)

29. logging日志

import logging

logging.basicConfig(level=logging.INFO)

logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")

30. asyncio异步

import asyncio

async def my_coroutine():
    print("Coroutine started")
    await asyncio.sleep(1)
    print("Coroutine finished")

loop = asyncio.get_event_loop()
loop.run_until_complete(my_coroutine())

31. heapq堆操作

import heapq

lst = [3, 1, 4, 1, 5, 9, 2, 6]

heapq.heapify(lst)
print(heapq.heappop(lst))  # 1
print(heapq.heappop(lst))  # 1
print(heapq.heappop(lst))  # 2

32. 类型注释

from typing import List, Tuple

def my_function(x: int, y: str) -> Tuple[int, str]:
    return x, y

def my_function2(lst: List[int]) -> int:
    return sum(lst)

33. hashlib哈希

import hashlib

s = "hello world"
md5 = hashlib.md5(s.encode()).hexdigest()
sha256 = hashlib.sha256(s.encode()).hexdigest()

print("MD5:", md5)
print("SHA256:", sha256)

34. 多重继承

class A:
    def foo(self):
        print("A")

class B:
    def foo(self):
        print("B")

class C(A, B):
    pass

c = C()
c.foo()  # 输出 "A"

35. 元类

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs['x'] = 42
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=MyMeta):
    pass

print(MyClass.x)  # 42

36. slots

class MyClass:
    __slots__ = ['x', 'y', 'z']
    
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

37. @property

class MyClass:
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

c = MyClass(42)
print(c.x)  # 42
c.x = 99
print(c.x)  # 99

38. super函数

class A:
    def foo(self):
        print("A")

class B(A):
    def foo(self):
        super().foo()
        print("B")

b = B()
b.foo()  # 输出 "A" 和 "B"

39. 抽象基类

from abc import ABC, abstractmethod

class MyABC(ABC):
    @abstractmethod
    def my_method(self):
        pass

class MyClass(MyABC):
    def my_method(self):
        print("MyClass.my_method() called")

c = MyClass()
c.my_method()

40. 描述符

class MyDescriptor:
    def __get__(self, instance, owner):
        return instance._x * 2

    def __set__(self, instance, value):
        instance._x = value

class MyClass:
    def __init__(self, x):
        self._x = x

    x = MyDescriptor()

c = MyClass(42)
print(c.x)  # 84
c.x = 99
print(c.x)  # 198

作者:spike

分类: Python

创作时间:2026-02-24

更新时间:2026-02-24