2

I am wondering if it is possible to create a notebook that is able to run code in both python2 and python3.

So far, I have a notebook in python2, but as I run python3 code in a cell, it is unable to run python2 code in other cells.

1 Answer 1

2

Use the %%python2 cell magic at the top of the cell to make the rest of the cell run in python2. Same with %%python3 for python3. You should only really need to use one though, as the one which is the native kernel shouldn't need to have it's magic declared.

In a python2 notebook:

Cell1:

%%python3
print("Hello world!")

Cell2:

print "Hello world!"
Sign up to request clarification or add additional context in comments.

3 Comments

My problem is that I use python2 throughout the notebook but a cell where I only need from __future__ import print_function. Following cells in python2 that use print "something" instead of print("something") return an error.
Thanks. So how can I use from __future__ import print_function in one cell without affecting the computation in other cells?
This is turning into a completely different question. Maybe just accept this totally fine answer and create a new one (if it doesn't exist yet). Also ask yourself if it's worth the hassle or if the code part that causes troubles might only need some round brackets removed or the import of the print_function removed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.