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

基于传入函数的变量做决策:Python 3新手函数调用报错问题

Fixing the NameError in Your Python Arithmetic Function

Hey there! Let's break down what's going wrong and fix that code of yours step by step.

Why You're Getting the Error

The NameError: name 'add' is not defined pops up because Python has no clue what add or mult are. You're trying to pass these as arguments to your arith function, but you never told Python what they represent—they aren't variables, functions, or any defined value in your code right now.

Here Are 3 Simple Fixes You Can Use

1. Use Strings to Identify Operations

This is the most straightforward approach for beginners. Pass operation names as strings, then check those strings inside your function:

def arith(x, y, operation):
    if operation == "add":
        return x + y
    if operation == "mult":
        return x * y

print(arith(x=2, y=3, operation="add"))  # Output: 5
print(arith(x=2, y=3, operation="mult")) # Output: 6

Just wrap add and mult in quotes to turn them into strings Python can recognize and compare against.

2. Pass Function Objects Directly

In Python, functions are "first-class citizens"—meaning you can pass them around like any other value. First define your add and mult functions, then pass them to arith:

def add(x, y):
    return x + y

def mult(x, y):
    return x * y

def arith(x, y, operation):
    # Call the function we passed as an argument
    return operation(x, y)

print(arith(x=2, y=3, operation=add))  # Output: 5
print(arith(x=2, y=3, operation=mult)) # Output: 6

This is more flexible—if you want to add a new operation later (like subtraction), you just write a new function and pass it in without changing the arith function itself.

3. Use Python's Built-in operator Module

Python has a built-in operator module that already has pre-written functions for common arithmetic operations. This saves you from writing your own add and mult functions:

import operator

def arith(x, y, operation):
    return operation(x, y)

print(arith(x=2, y=3, operation=operator.add))  # Output: 5
print(arith(x=2, y=3, operation=operator.mul))  # Output: 6

operator.add handles addition, operator.mul handles multiplication, and there are others like operator.sub (subtraction) and operator.truediv (division) if you need them later.

Which One Should You Choose?

If you're just starting out, go with the string method—it's easy to understand and tweak. As you get more comfortable with Python, try the function object or operator module approaches for cleaner, more flexible code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:34:35