我是一名初级 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
最佳答案
在函数定义后加一个空行,让解释器明白它已经完成。
>>> def f(x,y):
solution = x+y
return solution
>>> f(2,2)
4
关于python - 简单功能不起作用,看不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465811/