【问题标题】:Confusion as to function parameters [duplicate]关于功能参数的困惑[重复]
【发布时间】:2017-04-25 00:24:28
【问题描述】:

我正在尝试制作一个接受 2 个参数的简单函数,并使用“+”将它们相加。

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

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

【问题讨论】:

  • return result 并且您还需要调用该函数,例如my_calculation = do_plus(3, 7) 在函数之外。在函数内部为ab 提供硬编码值是没有意义的,您希望将它们作为参数 传递。此外,应该在函数内部的所有内容都应该缩进。
  • from operator import add as do_plus

标签: python function scope interactive


【解决方案1】:

您缺少缩进​​。

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)

【讨论】:

    【解决方案2】:

    很难从你的代码中分辨出来,因为缩进是关闭的,但是一个简单的加法函数可以是这样的:

    def addition(a, b):
      return a + b
    

    您接受参数ab,然后为它们分配值73,这样无论如何,它都会返回10

    【讨论】:

    • addition(5,None) ?
    【解决方案3】:

    试试这个:

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

    你可以调用你的函数“do_plus”传递参数并打印函数返回

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

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多