Skip to main content
 首页 » 编程设计

python之简单功能不起作用,看不到错误

2025年05月04日13bhlsheji

我是一名初级 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