简体   繁体   English

Python 3.10.6:调用用户定义的 function 时出现语法错误和名称错误

[英]Python 3.10.6: Syntax error and Name error when calling a user defined function

I'm using Python IDLE Shell 3.10.6, and this happens:我正在使用 Python IDLE Shell 3.10.6,这会发生:

def math(x,y):
    return x*y
math(1,2)
SyntaxError: invalid syntax
math(1,2)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    math(1,2)
NameError: name 'math' is not defined

Is this because Python 3.10.6 has a different syntax?这是因为 Python 3.10.6 有不同的语法吗? I've tried the same thing in Jupyter notebook and it worked perfectly.我在 Jupyter notebook 中尝试过同样的事情,并且效果很好。

Can anyone help me out please?谁能帮帮我? Thank you in advance!先感谢您!

This hasn't got anything to do with Python syntax, but quirks of the IDLE interactive shell.这与 Python 语法没有任何关系,而是 IDLE 交互式 shell 的怪癖。

In the interactive shell, you'll want to separate the definition of the function and the call into separate entries with an ENTER press, ie not so it reads在交互式 shell 中,您需要将 function 的定义和调用分离为单独的条目,按 ENTER 键,即不是这样它读取

>>> def math(x,y):
    return x*y
math(1,2)
SyntaxError: invalid syntax

(as it's attempting to parse the function to contain a trailing, unindented line) (因为它试图解析 function 以包含一个尾随的、未缩进的行)

but instead so it reads但相反,它显示为

>>> def math(x,y):
    return x*y

>>> math(1, 2)
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM