【问题标题】:Simple Function does not work, dont see the error简单功能不起作用,看不到错误
【发布时间】:2012-11-08 02:00:44
【问题描述】:

我是一名初级 Python 程序员,但已经编写了几个脚本,其中包括我定义自己的函数并使用它们的脚本。我似乎无法让任何用户定义的函数在 IDLE 中工作。想知道我是不是疯了/笨。有人可以解释以下结果吗?谢谢:

def f(x,y):
    solution = x+y
    return solution
f(2,2)
SyntaxError: invalid syntax
>>> a = f(2,2)

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a = f(2,2)
NameError: name 'f' is not defined

def g(x):
    solution = x + 2
    return solution
g(2)
SyntaxError: invalid syntax
>>> a = g(2)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    a = g(2)
NameError: name 'g' is not defined

【问题讨论】:

    标签: python function syntax-error


    【解决方案1】:

    在函数定义后添加一个空行,让解释器明白它已经完成了。

    >>> def f(x,y):
            solution = x+y
            return solution
    
    >>> f(2,2)
    4
    

    【讨论】:

    • 伙计,编辑并击败了我 - 如果可以的话,我会 +1 两次 :)
    猜你喜欢
    • 2023-03-23
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多