如何用python编写程序,学校图书馆新进一批图书,请用Python语言编写软件以存储这些图书的信息。图书信息主要指:图书名称,出版社,数量,单价。软件应具备以下主要功能: (1) 数据输入:输入图书信息。(2) 数据保存:能够将输入的信息以文件的形式保存到计算机中。(3) 数据查询:能够按照"图书名称"查询图书信息,也能够按照"单价"查询图书信息。(4) 数据修改:当输入数据出现误操作时,事后可以更改。软件至少应具有"数据输入"、"保存"、"查询"、"修改"、"退出"5项菜单
时间: 2023-08-07 21:39:35 浏览: 84
可以使用Python语言编写一个简单的图书管理系统,实现以上功能。下面是示例代码:
```python
import json
def menu():
print("1. 数据输入")
print("2. 数据保存")
print("3. 数据查询")
print("4. 数据修改")
print("5. 退出")
def input_book():
book = {}
book['name'] = input("请输入图书名称:")
book['publisher'] = input("请输入出版社:")
book['quantity'] = int(input("请输入数量:"))
book['price'] = float(input("请输入单价:"))
return book
def save_books(books):
with open('books.json', 'w') as f:
json.dump(books, f)
def load_books():
try:
with open('books.json', 'r') as f:
books = json.load(f)
except FileNotFoundError:
books = []
return books
def query_books_by_name(books, name):
result = []
for book in books:
if book['name'] == name:
result.append(book)
return result
def query_books_by_price(books, price):
result = []
for book in books:
if book['price'] == price:
result.append(book)
return result
def modify_book(books, index):
book = books[index]
book['name'] = input("请输入图书名称:")
book['publisher'] = input("请输入出版社:")
book['quantity'] = int(input("请输入数量:"))
book['price'] = float(input("请输入单价:"))
books[index] = book
def main():
books = load_books()
while True:
menu()
choice = input("请选择操作:")
if choice == '1':
book = input_book()
books.append(book)
elif choice == '2':
save_books(books)
print("保存成功!")
elif choice == '3':
query_choice = input("请选择查询方式:1.按照图书名称查询,2.按照单价查询:")
if query_choice == '1':
name = input("请输入图书名称:")
result = query_books_by_name(books, name)
elif query_choice == '2':
price = float(input("请输入单价:"))
result = query_books_by_price(books, price)
else:
print("无效选择!")
continue
if len(result) == 0:
print("没有找到匹配的图书!")
else:
print("共找到%d本匹配的图书:" % len(result))
for book in result:
print("图书名称:%s,出版社:%s,数量:%d,单价:%.2f" % (book['name'], book['publisher'], book['quantity'], book['price']))
elif choice == '4':
index = int(input("请输入要修改的图书编号:"))
if index < 0 or index >= len(books):
print("无效编号!")
else:
modify_book(books, index)
print("修改成功!")
elif choice == '5':
break
else:
print("无效选择!")
if __name__ == '__main__':
main()
```
这个程序使用了JSON格式来保存图书信息,可以将数据保存在文件中。用户可以选择按照图书名称或单价来查询图书信息,也可以修改已经输入的图书信息。
阅读全文