以下是一个示例代码,用于计算不得超过$2.00或者20%的金额,并选择较大的金额。
def calculate_amount(price):
max_amount = max(2.00, price * 0.2)
return min(price, max_amount)
# 测试示例
price1 = 1.50
price2 = 10.00
price3 = 100.00
amount1 = calculate_amount(price1)
amount2 = calculate_amount(price2)
amount3 = calculate_amount(price3)
print(amount1) # 输出 1.50,小于20%的金额
print(amount2) # 输出 2.00,超过20%的金额
print(amount3) # 输出 20.00,超过$2.00的金额
在上述示例代码中,calculate_amount
函数接受一个价格作为参数,然后根据条件计算出不得超过$2.00或者20%的金额,并返回最终的金额。使用max
函数选择出两者中较大的金额,然后使用min
函数选择出价格和最大金额中的较小值作为最终金额。最后,通过打印输出来验证代码的正确性。