简体   繁体   中英

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. Why doesn't the above code work?

Enter a blank line after "print x". Generally, the ... prompt indicates that Python expects further input for the current block, in this case the function f .

As pointed out by Iguananaut IPython has superior editing capabilities compared to the standard Python shell, for example tab auto completion.

You need to press enter twice after the last line to get back to a >>> prompt in which case you can enter new expressions.

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. It supports much better editing of multi-line statements, and even better still if you use the qtconsole or the notebook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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