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

Python收据生成器函数交互与return使用问题求助

Python收据生成器函数交互与return使用问题求助

你想要做一个计算顾客最终付款的程序,包含商品信息、折扣、税费和总价的计算,但现在运行代码时遇到了NameError,核心问题是没搞清楚函数的参数传递和return的正确用法,对吧?

先看你的原始需求注释:

#The total will be the price paid by the customer after the discount and the tax.
#Create a main function, getItem function, getDiscount function, getTaxRate function
#getTotal function. #Use pass through variables.

你的问题描述:
我想做这个小项目来提升自己的知识,但不知道怎么正确使用return函数让代码正常工作。


你的原始代码

print ("*****Jeremy's BBQ for You*****")
import datetime
now = datetime.datetime.now()
print(" ",now)
def main ():
    getItem()
    getItem2()
    getDiscount()
    getTaxrate()
    getTotal()
def getItem():
    item_name = input("Enter in the name of the purchased item: ")
def getItem2():
    item_price = float(input("Enter the price of the item being purchased: "))
    print (item_price)
def getDiscount():
    store_discount = item_price * float(.1)
    print ("You are recieving a 10% discount of: ",store_discount)
    return item_price
def getTaxrate():
    tax_rate = item_price* float(.06)
def getTotal(): 
    total = item_price+store_discount+tax_rate
main()
print ("6% Tax")

你遇到的错误

Traceback (most recent call last):
  File "/home/main.py", line 37, in <module>
    main()
  File "/home/main.py", line 20, in main
    getDiscount()
  File "/home/main.py", line 30, in getDiscount
    store_discount = item_price * float(.1)
                     ^^^^^^^^^^
NameError: name 'item_price' is not defined

你的疑问:
我猜这是因为我没有正确定义函数,让它们能被引用——我是不是需要用return函数?还有怎么正确用?是不是还要在定义函数的()里添加变量,同时加上return?


问题根源分析

你遇到的NameError是因为变量作用域的问题:每个函数里定义的变量(比如getItem2里的item_price)默认只能在这个函数内部用,其他函数(比如getDiscount)根本看不到它。另外你的函数之间完全没有数据传递,也没正确用return把需要的值传出去,所以后续函数都拿不到之前的变量。

修正后的代码和解释

我们需要把函数改成接收参数+返回需要的值的形式,让数据能在函数之间“传递”起来,就像接力赛一样:

print("*****Jeremy's BBQ for You*****")
import datetime
now = datetime.datetime.now()
print(" ", now)

def main():
    # 1. 先获取商品名称和价格,把函数返回的值存到变量里
    item_name = getItem()
    item_price = getItem2()
    # 2. 把价格传给折扣函数,拿到计算好的折扣金额
    store_discount = getDiscount(item_price)
    # 3. 把价格传给税费函数,拿到计算好的税费金额
    tax_rate = getTaxrate(item_price)
    # 4. 把所有需要的值传给总价函数,算出最终总价
    total = getTotal(item_price, store_discount, tax_rate)
    # 5. 统一输出所有结果,让收据更清晰
    print("\n--- 购物收据 ---")
    print(f"商品名称: {item_name}")
    print(f"商品原价: ${item_price:.2f}")
    print(f"10%折扣减免: ${store_discount:.2f}")
    print(f"6%税费: ${tax_rate:.2f}")
    print(f"最终应付总价: ${total:.2f}")
    print("(税费率为6%)")

def getItem():
    # 专门负责获取商品名称,获取后返回给调用它的地方
    item_name = input("Enter in the name of the purchased item: ")
    return item_name

def getItem2():
    # 专门负责获取商品价格,获取后返回给调用它的地方
    item_price = float(input("Enter the price of the item being purchased: "))
    return item_price

def getDiscount(price):
    # 接收外部传进来的价格参数,计算折扣后返回折扣金额
    store_discount = price * 0.1
    print(f"You are recieving a 10% discount of: ${store_discount:.2f}")
    return store_discount

def getTaxrate(price):
    # 接收外部传进来的价格参数,计算税费后返回税费金额
    tax_rate = price * 0.06
    return tax_rate

def getTotal(original_price, discount, tax):
    # 注意:总价是「原价 - 折扣 + 税费」,你之前的公式写反了折扣的加减!
    total = original_price - discount + tax
    return total

main()

关键知识点拆解

  1. 函数参数:比如getDiscount(price)里的price就是参数,调用的时候我们把之前拿到的item_price传进去,这样函数内部就能用这个值计算了。
  2. return的作用:每个函数做完自己的事,把需要给其他函数用的值return出去,比如getItem2()返回item_price,这样main函数就能把这个值存下来传给下一个函数。
  3. 变量作用域:尽量让每个函数只负责一件事(单一职责),不要依赖外部的变量,而是通过参数接收需要的数据,通过return输出结果,这样代码更清晰也不容易出错。
  4. 我帮你修正了总价的计算公式——折扣是要减去的,不是加上,不然顾客要多付钱啦😉

为什么这样改能解决问题?

现在每个函数都像一个分工明确的小工具:

  • getItem()专门拿商品名,返回给main函数
  • getItem2()专门拿商品价格,返回给main函数
  • getDiscount()需要价格才能算折扣,所以我们把价格传进去,算好后返回折扣金额
  • 最后main函数把所有拿到的数据传给getTotal()算出最终总价,再统一输出清晰的收据

这样所有数据都能正确传递,不会再出现“找不到变量”的错误了。

备注:内容来源于stack exchange,提问作者Norbor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:29:28