用case实现Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): 3 Enter the name of the user: Bob Bob borrows 12 book(s). Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): 4 Enter the name of the user: Bob Enter the number of books: -15 Positive integers only! Enter the number of books:
时间: 2023-06-27 14:04:58 浏览: 48
以下是使用Python编写的代码,实现了上述功能:
```
while True:
action = input("Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): ")
if action == "1":
print("The total number of books borrowed is:", total_books)
elif action == "2":
name = input("Enter the name of the user: ")
num_books = input("Enter the number of books borrowed: ")
while not num_books.isdigit() or int(num_books) <= 0:
print("Positive integers only!")
num_books = input("Enter the number of books borrowed: ")
borrowers[name] = borrowers.get(name, 0) + int(num_books)
total_books += int(num_books)
elif action == "3":
name = input("Enter the name of the user: ")
print(name, "borrows", borrowers.get(name, 0), "book(s).")
elif action == "4":
name = input("Enter the name of the user: ")
num_books = input("Enter the number of books: ")
while not num_books.isdigit() or int(num_books) <= 0:
print("Positive integers only!")
num_books = input("Enter the number of books: ")
borrowers[name] = borrowers.get(name, 0) + int(num_books)
total_books += int(num_books)
elif action == "5":
name = input("Enter the name of the user: ")
num_books = input("Enter the number of books: ")
while not num_books.isdigit() or int(num_books) <= 0:
print("Positive integers only!")
num_books = input("Enter the number of books: ")
if borrowers.get(name, 0) >= int(num_books):
borrowers[name] -= int(num_books)
total_books -= int(num_books)
else:
print("The user cannot return more books than they have borrowed!")
elif action == "6":
print("Quitting...")
break
else:
print("Invalid action!")
```
这段代码使用了一个while循环,让用户可以反复执行不同的操作,直到选择退出。在每个操作中,用户需要输入一些信息,例如用户名和借书数量。代码会对输入进行验证,确保输入的是正整数。如果输入不正确,代码会提示用户重新输入。每个操作完成后,代码会更新borrowers和total_books变量,以便下次操作时使用。