Python会员卡盈利判断函数开发及代码完善求助
会员卡折扣划算性判断程序修正
需求说明
需要编写一个基于def定义的Python程序,判断购买享受折扣的会员卡是否划算:
- 判断标准:折扣后购买成本 + 会员卡价格 ≤ 原购买成本
- 函数参数:总购买金额(欧元)、会员卡折扣百分比、会员卡价格
- 返回规则:
- 办卡可为用户节省x欧元时,返回x
- 办卡后总花费高于原购买价时,返回-x(x为多支出的金额)
- 输出需匹配示例格式:
Total purchase amount: 200 Discount percent: 5 Customer card price: 5 It’s better to get a card, you will save 5 euros
现有代码问题
用户已编写部分代码,但存在语法错误与逻辑问题,代码如下:
def customer_card_discount1(total_purchase_amount1, discount_percent1, customer_card_price1): new_price = (total_purchase amount1) * (100 - discount_percent1)/100 + (customer_card_price1) if new_price <= total_purchase amount1: return customer_card_price1 - new_price elif new_price > total_purchase amount1: return customer_card_price1 - new_price try: total_purchase_amount1 - int(input("Total purchase amount")) discount_percent1 - int(input("Discount percent")) customer_card_price1 - int(input("Customer card price"))
修正后的完整代码
def customer_card_discount(total_purchase_amount, discount_percent, customer_card_price): # 计算办卡后的总花费:折扣后商品总价 + 会员卡价格 discounted_goods_price = total_purchase_amount * (100 - discount_percent) / 100 total_cost_with_card = discounted_goods_price + customer_card_price # 计算差额:原总价 - 办卡后总价,正数为节省,负数为多花 saving = total_purchase_amount - total_cost_with_card return saving try: # 获取用户输入,匹配示例提示格式 total = int(input("Total purchase amount: ")) discount = int(input("Discount percent: ")) card_price = int(input("Customer card price: ")) result = customer_card_discount(total, discount, card_price) # 根据返回值输出对应提示 if result >= 0: print(f"It’s better to get a card, you will save {result} euros") else: print(f"It’s not worth getting a card, you will spend {abs(result)} euros more") except ValueError: # 处理非整数输入的异常 print("Please enter valid integer values.")
核心修正要点
- 语法错误修复:
- 变量名不能包含空格(如
total_purchase amount1改为合法的total_purchase_amount1) - 赋值操作必须用
=,而非输入代码里的- - 修正多行代码换行的语法问题,同时保证
if/elif代码块的正确缩进
- 变量名不能包含空格(如
- 逻辑修正:
- 原返回值计算逻辑错误,正确的差额应为
原总金额 - 办卡后总花费,正数代表节省,负数代表多支出
- 原返回值计算逻辑错误,正确的差额应为
- 功能完善:
- 增加异常处理,避免用户输入非整数导致程序崩溃
- 调整输入提示格式,与示例要求匹配
- 拆分计算步骤,增加注释提升代码可读性
内容的提问来源于stack exchange,提问作者Albina
相关产品推荐
相关产品推荐

