Python练习代码
时间: 2024-11-15 10:15:16 浏览: 9
python练习代码
Python练习代码通常是用于巩固学习和提升编程技能的小规模项目或练习示例。它们涵盖了许多主题,例如数据结构、算法、函数、类等。下面是一个简单的例子,展示如何创建一个迷你图书管理系统:
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def search_by_title(self, title):
return [book for book in self.books if book.title == title]
# 示例用法
book1 = Book("Python Crash Course", "Eric Matthes")
book2 = Book("Fluent Python", "Luciano Ramalho")
library = Library()
library.add_book(book1)
library.add_book(book2)
title_search = input("请输入书名查找:")
result = library.search_by_title(title_search)
if result:
print(f"找到了以下书籍:")
for book in result:
print(book.title, " - ", book.author)
else:
print("未找到匹配的书籍。")
```
阅读全文