Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter Notebook Input Line Executed Before Print Statement

Hello I am working on improving my python skills in Jupyter Notebook and I am having a frustrating issue. In a larger piece of code, my input statements are being executed before the print statements although the print statement is first in the code block. Is there a way to fix this in Jupyter Notebook? I am doing a tutorial course and want to continue using this IDE. Please see attached image.

Python Input issue

like image 852
Joshy Tea Avatar asked May 20 '18 20:05

Joshy Tea


People also ask

What does %% capture do in Jupyter?

What does %% capture do in Jupyter? Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams.

How do you run a specific line in a Jupyter Notebook?

To run a piece of code, click on the cell to select it, then press SHIFT+ENTER or press the play button in the toolbar above. Additionally, the Cell dropdown menu has several options to run cells, including running one cell at a time or to run all cells at once.

Can Jupyter Notebook take inputs?

Jupyter Notebooks have a range of widgets to make these kinds of changes more user-friendly, aesthetically pleasing, and intuitive. In addition to all these benefits, you will also learn UI concepts and test code that handles user input.

How do you debug a line by line in Jupyter Notebook?

Debug code in Jupyter notebooksSet the breakpoints in the selected cell and press Alt + Shift + Enter for Windows or ⌥⇧↩ for macOS. Alternatively, you can right-click the cell and select Debug Cell from the context menu.


2 Answers

It looks like a race condition between two streams. One possible, unsastifying solution is to wait a bit before executing input:

import time
print("Welcome")
time.sleep(0.05)
input("yes")

enter image description here

like image 62
Eric Duminil Avatar answered Nov 15 '22 01:11

Eric Duminil


When I flush the print statement to force it to display, it works for me:

print("Welcome", flush = True)
input("yes")
like image 30
eric Avatar answered Nov 15 '22 00:11

eric