You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码中+=累加与if判断失效问题求助

露营车定价代码问题排查

你的代码核心问题在于判断用户输入是否为"Y"或"y"的逻辑错误,另外还有一处拼写小问题:

错误点分析

  1. 条件判断逻辑错误:
    你写的if Island == "Y or y"是在判断变量是否等于字符串"Y or y"(包含空格和"or"的完整字符串),而不是判断输入是否是"Y"或者"y"。用户输入的只能是单个字符"Y"/"y"/"N"/"n",所以这个条件永远不会成立,导致额外费用无法累加。
    同理,Heater == "Y or y"也存在同样的问题。

  2. 拼写小问题:
    输入提示里的"Do you want and Island?"应该改为"Do you want an Island?",属于笔误,不影响代码运行但影响用户体验。

修正后的代码

Size = int(input("What size camper do you want? Size in feet. \n"))
# 修正拼写错误:and → an
Island = input("Do you want an Island? y or n \n")
Heater = input("Do you want tankless water heater? y or n \n")

price = 0

if Size <= 30:
    price += 50000
elif Size <= 40:
    price += 60000
else:
    price += 80000

# 修正条件判断:统一转大写后判断,兼容Y/y两种输入
if Island.upper() == "Y":
    if Size <= 30:
        price += 500
    else:
        price += 800

# 同理修正Heater的判断逻辑
if Heater.upper() == "Y":
    if Size <= 30:
        price += 1000
    else:
        price += 1500

print(f"Your total for a new camper will be ${price}!")

其他可选写法

除了用upper()转大写,也可以直接判断输入是否在指定列表里:

if Island in ["Y", "y"]:
    # 后续逻辑不变

两种写法都能正确识别用户输入的"Y"或"y",upper()写法更简洁,还能兼容用户误输入的大小写混合情况。

内容的提问来源于stack exchange,提问作者KawiGirl06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:11:27