You need to enable JavaScript to run this app. Python如何正确获取两个输入值 修复盈亏计算代码的NameError报错
优惠活动
大模型
产品
解决方案
定价
更多

Python如何正确获取两个输入值 修复盈亏计算代码的NameError报错

报错本质解析
  • 触发NameError的核心原因是:代码里直接写input(costPrice, sellingPrice)时,costPrice、sellingPrice两个变量从来没有被定义、赋值,就直接被当成input()的参数传入,Python根本识别不到这两个变量,自然抛出名称错误。
  • 另外Python内置的input()函数仅支持传入1个参数:也就是给用户看的输入提示文本,不支持一次传多个变量/多个值,本身的函数用法也用错了。
  • 额外提醒:input()默认返回的是字符串类型,哪怕正确拿到了输入,不转成数值类型的话,后续做大小比较、差额计算都会触发类型不匹配的报错。
正确的双输入实现方式

需要分别获取两个价格的输入,拿到字符串后转成数值类型(用float支持小数形式的商品价格),再赋值给对应的变量:

# 分别获取成本价、售价,同步完成类型转换
costPrice = float(input("请输入商品成本价:"))
sellingPrice = float(input("请输入商品售价:"))
修复后可运行的完整代码
# Profit and Loss
# Function to calculate Profit.
def Profit(costPrice, sellingPrice):
    profit = (sellingPrice - costPrice)
    return profit

# Function to calculate Loss.
def Loss(costPrice, sellingPrice):
    # 调整内部变量名,避免和函数名重名导致的作用域混淆
    loss_amount = (costPrice - sellingPrice)
    return loss_amount

if __name__ == "__main__":
    # 替换原来错误的input调用
    costPrice = float(input("请输入商品成本价:"))
    sellingPrice = float(input("请输入商品售价:"))

    if sellingPrice == costPrice:
        print("No profit nor Loss")
    elif sellingPrice > costPrice:
        print(Profit(costPrice, sellingPrice), "Profit")
    else:
        print(Loss(costPrice, sellingPrice), "Loss")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 14:06:03