简体   繁体   English

Python-如何在Python Shell中定义函数?

[英]Python - how can I define a function from within the Python shell?

>>> def f(x):
...     print x
... f('hello')
  File "<stdin>", line 3
    f('hello')
    ^
SyntaxError: invalid syntax
>>> 

I'm at the prompt in the Python shell. 我在Python Shell中出现提示。 Why doesn't the above code work? 上面的代码为什么不起作用?

Enter a blank line after "print x". 在“打印x”之后输入空白行。 Generally, the ... prompt indicates that Python expects further input for the current block, in this case the function f . 通常, ...提示表明Python希望为当前块(在本例中为f

As pointed out by Iguananaut IPython has superior editing capabilities compared to the standard Python shell, for example tab auto completion. 正如Iguananaut所指出的,与标准的Python Shell相比,IPython具有更出色的编辑功能,例如选项卡自动完成。

You need to press enter twice after the last line to get back to a >>> prompt in which case you can enter new expressions. 您需要在最后一行之后按Enter键两次,以返回>>>提示符,在这种情况下,您可以输入新的表达式。

Also, if you're going to by typing lots of multi-line expressions into the interpreter you should give IPython (now with funding!) a look. 另外,如果要在解释器中键入很多多行表达式,则应该给IPython (现在有资金!)看一下。 It supports much better editing of multi-line statements, and even better still if you use the qtconsole or the notebook. 它支持对多行语句进行更好的编辑,如果使用qtconsole或笔记本,它甚至更好。

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

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