如何在Python书店程序中添加用户输入校验规则?
实现书店程序的输入校验功能
以下是添加了所有校验规则的完整代码:
flag = True books = [] while flag: # 获取输入并去除首尾空格 title = input("Title: ").strip() author = input("Author: ").strip() purchase_price_input = input("Purchase_Price: ").strip() sell_price_input = input("Sell_Price: ").strip() # 校验所有输入项非空 if not title or not author or not purchase_price_input or not sell_price_input: print("所有输入项不能为空,当前条目未记录") else: try: # 转换价格为浮点数,同时处理非数字输入的情况 purchase_price = float(purchase_price_input) sell_price = float(sell_price_input) # 校验价格大于0 if purchase_price <= 0 or sell_price <= 0: print("进货价和售价必须大于0,当前条目未记录") # 校验进货价低于售价 elif purchase_price >= sell_price: print("进货价必须低于售价,当前条目未记录") # 所有校验通过,记录书籍信息 else: margin = ((sell_price - purchase_price) / purchase_price) * 100 book = (title, author, purchase_price, sell_price, margin) books.append(book) print("书籍信息已成功记录") except ValueError: print("价格必须是有效数字,当前条目未记录") # 校验继续输入的选项,直到输入有效 while True: continues = input("Do you want to enter more books? y/n ").strip().upper() if continues in ('Y', 'N'): break print("请输入有效的选项:y/Y 或 n/N") # 处理退出逻辑 if continues == 'N': print("已记录的书籍信息:") for book in books: print(f"标题: {book[0]}, 作者: {book[1]}, 进货价: {book[2]}, 售价: {book[3]}, 利润率: {book[4]:.2f}%") flag = False
校验规则实现说明
- 非空输入校验:对每个输入执行
strip()去除首尾空格后,通过if not 输入内容判断是否为空,只要有一个空项就跳过当前条目记录 - 价格合法性校验:
- 用
try-except捕获非数字输入的异常,避免程序崩溃 - 检查进货价和售价是否均大于0,不符合则不记录
- 检查进货价是否低于售价,不符合则不记录
- 用
- 继续输入选项校验:用内部循环持续询问用户,直到输入的内容属于
y/Y/n/N(统一转大写简化判断逻辑),才退出循环 - 修正了原代码的逻辑错误:原代码中
if continues == 'Y' or 'y'的写法会永远为真,改为用in判断是否在有效选项集合中
内容的提问来源于stack exchange,提问作者Captain
相关产品推荐
相关产品推荐

