Input Function Not Working

Hi,

Input function is not working in Jupyter Notebook.As soon as I am running input function, it gets crash and if I am entering any other code after that, it will not run.
Please suggest as I tried to uninstall and then again install but still faces the same issue.

1 Like

Hi @Bhawna, can you show more info about your question?
Do you mean input() function?

1 Like

Hi,

I want to take input from user and below is the code:
Value= input(“enter a number”)
print(value)

After running this code its gets hanged and if I am writing and other code after this its not executing.

1 Like

Hi, I understand your question.
It’s not a bug. The input() function will block your programe until you input some thing from your keyboard. If you don’t, the programe will just wait there, so the code after input() will not work. It’s also because they use the same ipythen kernel.
I think that the other way to make your code work is using multithreading or coroutine.

3 Likes

Thank you so much bro i am also facing this problem but now i am satisfied…again thanks alot

im facing a problem with the int(input()) function

That’s because I suspect you aren’t running an actual typical Python-based kernel and instead are using JupyterLite, perhaps. (It uses web assembly and a lot of the normal features of Python are not supported in the default manner. It is noted as very experimental. See the ‘Status’ note here.)

However, you included screenshot that doesn’t show enough and don’t describe the system where you are working. Generally, a screenshot doesn’t suffice and if you do include one be sure to include the information on the type of kernel, which should show up in the upper right side.

Try the following for your input line:

a = int(await input("number please:"))

Depending on the version running that may help. There was a time that worked, then didn’t wok, and now seems back to working. Please see here and the post below it for more potential pitfalls. Actually see here for more details in a better post about await input() use.

I’d suggest using a typical, full-Python kernel backed system for testing out when you may have encountered a JupyterLite limitation, by going here and pressing launch binder. Then when the session comes up in your browser, open a new notebook to get a remote notebook running with a full, typical Python-backed kernel on a temporary remote system, and paste in the code you are trying. That way you’ll know the root cause and can look for JupyterLite/Pyodide-compatible work arounds or decide to just use a typical Python-backed kernel for your efforts.

1 Like

I tried Jupyter Notebook, not Lit. It does not work. Adding await could eliminate that error message. But for input in a loop like the following guess my number game, it asks for one number and stopped the loop.

import random

secret = random.randint(0, 10)
while True:
    num = int(await input("number please:"))
    if num == secret:
        print("You got it!")
        break
    else:
        print("Too small" if num < secret else "Too big")

What specific error did you get that you are referencing here? And what was the kernel exactly?
In a true Python kernel, you don’t need the await input(). This works with just num = int(input("number please:")) in typical ipykernel. The above suggestion for await input() was with the pyodide kernel.
See your code working without it in ipykernel in Jupyter Notebook 7.1, Jupyter Notebook NbClassic, and JupyterLab:



JupyterLab Versions 3.48 and 4.1.4 both worked. I only provided the image from 3.4.8.

That code run in the images above:

import random

secret = random.randint(0, 10)
while True:
    num = int(input("number please:"))
    if num == secret:
        print("You got it!")
        break
    else:
        print("Too small" if num < secret else "Too big")

I am not sure how I could start a “true Python kernel”. I accessed jupyter.org and chose Jupyter Notebook as the highlight in the following screenshot.

I tried to check the available kernels by clicking the Pyodide button at the top right corner of the screen, but found no other options there.

The error I got is exactly as Input Function Not Working - #6 by Arjun_Rajesh

Okay, it was JupyterLite. That is using the Pyodide kernel.

In the screenshot you show of the ‘Try Jupyter’ page, the paragraph directly above where you highlighted Jupyter Notebook says with warnings:

:warning:Experimental :warning: several of the environments below use the JupyterLite project to provide a self-contained Jupyter environment that runs in your browser. This is experimental technology and may have some bugs, so please be patient and report any unexpected behavior in the JupyterLite repository."

Anyway, this explains why you are seeing the need for await().

I suggested how to do that in the last paragraph of the post right above yours from today.

I’ll add that if the full Python kernel is one you want, you can set up GitHub repos or gists to already install the things you want using configuration files that the MyBinder service recognizes that often just boil down to listing what you need. Examples that you can launch with the dependencies listed in requirements.txt already by pressing ‘launch binder’ at the sites:

And keep in mind those are temporary sessions. If you make anything useful, download it to your local system immediately. You can upload notebooks you have to a fresh temporary Jupyter session.



As for the issue with your code with num = int(await(input("number please:"))) …

The easiest solution is to remove the await() and use a full Python kernel (ipykernel) using the method I said above.

As for the issue with your code with num = int(await(input("number please:"))), the input part is supposed to be await input(), see here.

If you make a cell with that as the content:

num = int(await(input("number please:")))

And then run it and enter a number. In the next cell you can put num in the cell and execute it and it will give you the value.

But as you’ve found you cannot do the loop you want to do using JupyterLite / Pyodide kernel at this time. See here for much the same question in a less complex context compared to your while loop in the same cell. Note that putting type(raw) after the await input() line doesn’t result in displaying the type in the previous cell.

And the second after await the code is not processed further

The reply is there:

We did not find a way around this for now. But if you have ideas please share them in the issue I just mentioned

In theory there is complex way to do it with a service worker; however, at this time it remains a challenge to make it something closer to what is expected. More about what is going on and options in JupyterLite / Pyodide here.

This is super helpful! Thank you, @fomightez!

That launch binder button is particularly helpful. It is such a small icon and so humble. :smiley: I am wondering why jupyter.org does not have that button on the Try Jupter page.

I also appreciate your patient explanation about await. I copied that parenthesis from your earlier example. But I noticed that you updated that example kindly.

The main examples for Jupyter Notebook and JupyterLab used to use MyBinder-served sessions but it was too taxing on the MyBinder system and when JupyterLite came along it was seen as a way to let users ‘try’ the interface without needing to run a remote machine.

From the ‘Try Jupyter’ page, you can still use MyBinder-served sessions. If you hover over some of the other tiles like Voila and the ones under ‘Kernels’, towards the bottom of the page there. The easiest one to use an ipykernel there is to click on the ‘Julia’ tile to launch that example and when the session comes up, switch the kernel to the ipykernel using ‘Kernel’ > ‘Change Kernel’ > ‘Python 3 (ipykernel)’ from the File menubar along the top. The Voila one isn’t easy to switch out of the Voila rendering although it is possible to get to Jupyter from there using the URL.

Alternative to input() that works in JupyterLite/pyodide

OP’s code can be written like this below to use ipywidgets to let the user guess the number and that works in JupyterLite / Pyodide because ipywidgets work in JupyterLite:

import ipywidgets as widgets
from IPython.display import HTML
import random

secret = random.randint(1, 10)
guessed_correctly = False

slider = widgets.IntSlider(
    value=0,
    max= 10,
    description='Slide to Your Guess:',
    continuous_update=False,
    style= {'description_width': 'initial'},
)


def on_value_change(change):
    global guessed_correctly
    if not guessed_correctly:
        if slider.value == secret:
            guessed_correctly = True
            output.update(HTML("You got it!"))
        else:
            output.update(HTML("Too small" if slider.value < secret else "Too big"))


output = display(HTML("The secret number is a number between 1 and 10.<br>Click and drag the slider from zero to your guess and then release the mouse button to submit your guess."), display_id=True)
display(slider)

slider.observe(on_value_change, names='value')

Importantly, besides working in JupyterLite / pyodide that can be customized extensively and is more functionally polished, modern, & interactive from the get-go than the legacy console-based input() method. Perhaps even more important for developing code in the Jupyter ecosystem is that same code will be useable in both a typical, full Python kernel (ipykernel) and pyodide, where ipywidgets as been installed. Below I provide more details about that and a place to run it in JupyterLite right now. (Currently ipywidgets was having an issue in the stable branch of JupyterLite, yet a fixed version is available.)

An alternative implementation using ipywidgets to enter the guesses with a reset button is in a gist here and that works in JupyterLite / Pyodide because ipywidgets work in JupyterLite. Below is a version of using ipywidgets to enter the guesses without the reset button because things are less complex, yet still fairly complex compared to the initial-input() based example and so I thought another step above the simpler version above would be informative to see the progression. Both are based on here primarily with some extras from here, because ipywidgets function in JupyterLite. (At present you can try it with ipywidgets in JupyterLite by clicking here and when that session comes up open a new notebook, let the busy indicator in the the upper right go to not busy, and then run %pip install -q ipywidgets in a cell followed by the code examples here. You have to use that version of JupyterLite for now because ipywidgets isn’t installing in the stable JupyterLite correctly at this time. That is temporary and will eventually be fixed on the main, stable branch, too.):

import ipywidgets as widgets

import random
max_secret = 10
secret = random.randint(1, max_secret)
guesses_allowed = 3
guesses_made = 0
game_still_going = True

# to leave out the quotes around strings sent to `ouptut.update()`, based on
# https://stackoverflow.com/a/70130979/8508004
class printer(str):
    def __repr__(self):
       return self

slider = widgets.IntSlider(
    value=0,
    min=0,
    max= max_secret,
    step=1,
    description='Slide to Your Guess:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    style= {'description_width': 'initial'},
    readout=True,
    readout_format='d'
)


def on_value_change(change):
    global guesses_allowed
    global guesses_made
    global game_still_going
    if game_still_going and (guesses_made < guesses_allowed - 1):
        guesses_made += 1
        if slider.value == secret:
            game_still_going = False
            output.update(printer(f'You win!\nYou guessed on your guess #{guesses_made} the number ' + str(slider.value) + f". The secret is: {secret}!\nRun the cell above to see if you are so lucky next time." ))
        else:
            output.update(printer(f"Guess #{guesses_made}:\nToo small" if slider.value < secret else f"Guess #{guesses_made}:\nToo big"))
    elif game_still_going:
        if slider.value == secret:
            game_still_going = False
            output.update(printer(f'You win!\nOn the last of your {guesses_allowed} guesses, you guessed ' + str(slider.value) + f"! The secret was: {secret}" ))
            
        else:
            game_still_going = False
            output.update(printer(f'Sorry. You lose!\nYou failed to guess the number in {guesses_allowed} guesses. Your last guess was ' + str(slider.value) + f". The secret was: {secret}\nRun the cell above to try the guessing game again." ))
    else:
        output.update(printer("THE GAME ENDED ALREADY.\nRun the cell above to try the guessing game again." ))

output = display(printer(f"The secret number is a number between 1 and {max_secret}.\nClick and drag the slider from zero to your guess and then release the mouse button to submit your guess.\nYou have three tries. You'll get a hint after each wrong guess."), display_id=True)
display(slider)

slider.observe(on_value_change, names='value')


IDEA THAT WAS-IN-PROGRESS (NOT WORKING YET!):
I was working on working this out having a timer without input() by using ipywidgets, like here:

import ipywidgets as widgets
import asyncio

import random
secret = random.randint(0, 10)
guesses_allowed = 3
# asyncio guess based on https://discourse.jupyter.org/t/is-it-possible-to-get-the-current-value-of-a-widget-slider-from-a-function-without-using-multithreading/15524/2?u=fomightez
slider = widgets.IntSlider(
    value=0,
    min=0,
    max=10,
    step=1,
    description='Your Guess:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    style= {'description_width': 'initial'},
    readout=True,
    readout_format='d'
)

async def select_guess(slider, output):
    i = 0
    while (i < guesses_allowed + 1):
        i = i+1
        if slider.value == secret:
            output.update('DONE ' + str(slider.value) + f" secret was: {secret}" )
        else:
            output.update(f"Guess #{i} (Secret:{secret}): Too small" if slider.value < secret else "Too big")
        await asyncio.sleep(5.1)
        #output.update(f"Guess #{i}: Too small" if slider.value < secret else "Too big")

output = display("Click and drag the slider to your guess and then release the mouse button to submit your guess. You have three tries. You get a hint after each wrong guess.", display_id=True)
display(slider)

asyncio.create_task(select_guess(slider, output));


how I solve this issue?

You need to enter a value in the input box and press Enter. See the animation in Rewrite "pending input" popup to be clearer ¡ Issue #16320 ¡ jupyterlab/jupyterlab ¡ GitHub

1 Like

Screenshot 2024-08-27 021549
Well here it is if you are using Jupyter notebook on vs code the this type of window should appear at the top where you can enter the input the same will be for the Jupyter actuall environment because they are eventually the same.