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

Python报错Name 'carbs'未定义,output函数参数调用问题求助

问题排查与解决

首先,你遇到的NameError: name 'carbs' is not defined错误,根源非常直接——你在调用output()函数时用的变量名,和实际接收输入的变量名完全不匹配。

看你的main()函数代码:

carbs_input = int(input("Carbohydrate content: "))
fat_input = int(input("Fat content: "))
pro_input = int(input("Protein content: "))
fiber_input = int(input("Fiber content: "))
output(carbs, fat, pro, fiber)  # 这里用的carbs、fat等变量根本没定义!

你接收用户输入的变量是carbs_input、fat_input、pro_input、fiber_input,但调用函数时却写了carbs、fat、pro、fiber——这些变量从未被赋值过,Python自然找不到它们。


第一步:修复变量名不匹配问题

把调用语句改成用你实际定义的输入变量即可:

output(carbs_input, fat_input, pro_input, fiber_input)

第二步:修复output()函数里的逻辑bug

除了上面的直接错误,你的output()函数还有一个条件判断的逻辑漏洞:

elif(final < 500 and final <= 100):

这个条件永远不会触发——因为前面已经判断过final < 100的情况,剩下的final必然是≥100的,所以这个分支完全无效。你想要的应该是卡路里在100到500之间时输出汉堡,可以把这个条件改成:

elif(final >= 100 and final < 500):

或者更简洁的写法,因为前面已经排除了≥500和<100的情况,直接用else就行:

def output(carbs, fat, pro, fiber):
    carbs = carbs*4
    pro = pro*4
    fat = fat*9
    fiber = fiber*4
    final = carbs + fat + pro - fiber
    if(final >= 500):
        print("Food: ", "Total Calories: ", final)
    elif(final < 100):
        print("Food: Salad", "Total Calories: ", final)
    else:  # 剩下的就是100≤final<500的情况
        print("Food: Hamburger", "Total Calories: ", final)

第三步:验证修复后的完整代码

修复后的代码如下,现在运行输入数值就能正常计算并输出结果了:

def output(carbs, fat, pro, fiber):
    carbs = carbs*4
    pro = pro*4
    fat = fat*9
    fiber = fiber*4
    final = carbs + fat + pro - fiber
    if(final >= 500):
        print("Food: ", "Total Calories: ", final)
    elif(final < 100):
        print("Food: Salad", "Total Calories: ", final)
    else:
        print("Food: Hamburger", "Total Calories: ", final)

def main():
    print('''___________ .___ _________ .__ .__ __
\_ _________ ____ __| _/ \_ ___ \_____ | | ____ __ __| | _____ _/ |_ ___________
| __)/ _ \ / _ \ / __ | / \ \/\__ \ | | _/ ___\| | | | \__ \\ __/ _ \_ __ \
| \( <_> ( <_> / /_/ | \ \____/ __ \| |_\ \___| | | |__/ __ \| |( <_> | | \/
\___ / \____/ \____/\____ | \______ (____ |____/\___ |____/|____(____ |__| \____/|__| \/
\/ \/ \/ \/ \/ ''')
    print("ADD CARBOHYDRATES, FAT, PROTEIN, AND FIBER")
    carbs_input = int(input("Carbohydrate content: "))
    fat_input = int(input("Fat content: "))
    pro_input = int(input("Protein content: "))
    fiber_input = int(input("Fiber content: "))
    output(carbs_input, fat_input, pro_input, fiber_input)

main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:42:38