Python 关于函数参数的混淆

Python 关于函数参数的混淆,python,function,scope,interactive,Python,Function,Scope,Interactive,我试图创建一个简单的函数,它接受两个参数,并使用+,将它们相加 def do_plus (a,b): a=3 b=7 result = a + b print (result) 但是,我没有返回任何值,函数被执行,但没有显示任何输出。您缺少缩进 a=3 b=7 def do_plus (a,b): result =a+b print (result) # and you have to call the function: do_plus(a,b

我试图创建一个简单的函数,它接受两个参数,并使用+,将它们相加

def do_plus (a,b):
    a=3
    b=7
    result = a + b
    print (result)

但是,我没有返回任何值,函数被执行,但没有显示任何输出。

您缺少缩进

a=3
b=7
def do_plus (a,b):
    result =a+b
    print (result)
# and you have to call the function:
do_plus(a,b)
您可能希望将逻辑与输入/输出分开,如下所示:

def do_plus(a, b):
    result = a + b
    return result

res = do_plus(3, 7)
print(res)

很难从代码中分辨,因为缩进已关闭,但简单的加法函数可以是:

def addition(a, b):
  return a + b
您正在接受参数a和b,但随后将其赋值为7和3,这样无论发生什么情况,它都将返回10。

尝试以下操作:

def do_plus (a,b):
    print=a+b
do_plus(3, 7)
您可以调用函数do_plus传递参数并打印函数返回值

注意结果之前的空格在python中很重要,脚本的标识

返回结果,您还需要调用函数,例如my_calculation=do_plus3,7在函数之外。在函数中为a和b提供硬编码值没有意义,您希望将它们作为参数传递。此外,应该在函数中的所有内容都应该缩进。从运算符导入添加为dou加上选项5,无?