How To Paste Code in Python Interpreter? Hint: Use ipython

IPython
IPython
IPython to paste code

If you have formatted code block with proper indentation and want to test it by copying and pasting on a python interpreter, you will be frustrated at Python for complaining at you. iPython offers great solutions coding with Python and for copying and pasting the code on the terminal.

One useful command in iPython to play with code block is “%cpaste”. To execute a code block, Type “%cpaste” on the iPython interpreter, it will say ” Pasting code; enter ‘–‘ alone on the line to stop.” Basically, then you just paste your code block and in the next new line type “–” or “Ctrl-D” to execute the code blog. For example

In [8]: %cpaste
Pasting code; enter ‘–‘ alone on the line to stop.
:>>> for i in range(100):
:>>>      print(i)
:–

The “%cpaste” offers much more to handle python code snippets. For example, one can assign a python code block to a variable by passing the variable as argument to “%cpaste”. For example ,”%cpaste myCodeBlock’, assigns the pasted code to the variable “myCodeBlock”.

[update] If you are working with latest version, you don’t even need “%cpaste”, you can paste the code chunk right in to your terminal.

Jupyter

If you are not interested in working with terminal, “jupyter notebook”, previously known as “ipython notebook” is the best option.