Running Python in the VS Code Interactive Window#

In this course, the way we run Python code in Visual Studio Code may be a little different from what you’ve seen in other Python courses on Coursera, including the first course in this specialization.

The Default VS Code Behavior#

The default behavior of Visual Studio Code (VS Code) is to allow users to run their code either by running the full file, or by sending code to the standard Python console one or more lines at a time.

Running whatever file is open is accomplished by clicking the play button in the top right corner of the window, which causes VS Code to execute the currently active Python file all at once:

basic run-file

In effect, this is precisely the same as what would happen if you opened a terminal window and typed python (replacing with the name of the file you have open).

To open an interactive Python session and run your code a few lines at a time, you normally just have to highlight the code you want to run and type shift-enter, which will cause VS Code to open a new python session if (one is not already open) and run the highlighted code there:

basic interactive terminal

The Interactive Window#

While powerful, this basic console (the interactive window with the familiar >>> prompt) has a number of major limitations. Some of these are small—no syntax highlighting, no formatting of help files, etc.—but one limitation is too big for our purposes in this course: it can’t display visualizations!

With that in mind, in this course when you highlight code and type shift-enter, rather than the basic console opening up with a >>> prompt, all of the VS Code instances have been configured to run the code in what VS Code calls the Interactive Window:

interactive window

Most of the time, you’ll find that the Interactive Window works the same as the basic python console, even if it looks different. But when the time comes to do things like plot figures or manipulate images, its value becomes quickly evident:

interactive window loads and image

Interactive Window and Jupyter#

If you’ve heard of Jupyter Notebooks, you may notice that this interface feels eerily familiar—and it should! Honestly, the Interactive Window probably should have just been named the “Jupyter Console” because that’s what it is behind the scenes—Jupyter! VS Code just created a place to see Jupyter output cells that is outside a notebook.

(If you’ve never heard of Jupyter Notebooks, don’t worry about it—we’ll talk more about them when the time comes.)

Changing what Shift-Enter Does#

If you’re working with VS Code on your own computer and want to enable this behavior, or want to know how to change the default behavior of shift-enter back, it’s easy—just open your settings and search for the “Send Selection to Interactive Window” setting for the Jupyter extension.

Change Interactive Window Keyboard Shortcut