dec*_*247 3 python cmd syntax-error python-3.x windows-10
我正在尝试在 Python REPL 上定义一个函数。每次尝试运行以下代码时,都会出现语法错误。
代码:
def hello():
print ("Hello!")
hello()
Run Code Online (Sandbox Code Playgroud)
错误:
C:\Users\~\Desktop>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello():
... print ("Hello!")
... hello()
File "<stdin>", line 3
hello()
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我在 stackoverflow 上遇到的一个可能的解释是这篇文章Python Error : File "<stdin>",它说我无法从 Python 解释器运行脚本。如果这是真的,为什么会这样?即,如果我能够在 cmd 窗口中运行 >>>2+2,为什么我不能运行“def”函数?希望在这一点上寻求澄清 - 谢谢!
编辑:将错误放在文本中,而不仅仅是图片。
定义函数后按 Enter 键一次(即输入一个空行)。本质上,这让 Python 知道您已经完成了对函数的定义。
>>>再次看到后,您可以调用您的函数。
请参阅图片,了解正确完成后的外观: