在Python命令行上定义函数时的语法错误 [英] Syntax error when defining a function on the Python command line

查看:112
本文介绍了在Python命令行上定义函数时的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python REPL上定义一个函数。每次尝试运行以下代码时,都会出现语法错误。



代码:

  def hello():
打印( Hello!)
hello()

错误:

  C:\Users\〜\Desktop> python 
Python 3.6.5(v3.6.5:f59c0932b4,Mar 28 2018,16:07:46)[win32 MSC v.1900 32 bit(Intel)]
键入帮助,版权,信用或许可以获取更多信息。
>> def hello():
...打印( Hello!)
... hello()
文件< stdin>,第3行
hello()
^
SyntaxError:语法无效

在其中说我无法从Python解释器运行脚本。如果是这样,为什么会这样呢?即如果我可以在cmd窗口中运行>>> 2 + 2,为什么我不能运行 def功能?希望在这一点上寻求澄清-谢谢!



编辑:在文本中输入错误,而不仅仅是图片。

解决方案

在定义函数后按一次Enter(即输入一个空白行)。本质上,这使Python知道您已经完成了定义函数的工作。



再次看到>>> 后,就可以调用函数了。



查看图片以了解正确完成后的外观:




I am trying to define a function on the Python REPL. Every time I try to run the below code, I get a syntax error.

Code:

def hello():
    print ("Hello!")
hello()

Error:

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

A possible explanation I've come across on stackoverflow is this post Python Error : File "<stdin>" where it says I can't run scripts from the Python interpreter. If that's true, why is that the case? I.e. if I'm able to run >>>2+2 in the cmd window, why am I not able to run a 'def' function? Hoping to look for clarification on this point - Thanks!

Edit: Put the error in text, not just the pic.

解决方案

Press enter once after defining your function (that is, enter one blank line). Essentially, this lets Python know that you are done defining your function.

Once you see >>> again, you can call your function.

See the picture for how it should look when done right:

这篇关于在Python命令行上定义函数时的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆