I would like to read data from the keyboard in python
I try this:
nb = input('Choose a number')
print ('Number%s \n' % (nb))
But it doesn't work, neither with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen.
Do you know why?
input([prompt])
is equivalent toeval(raw_input(prompt))
and available since python 2.6As it is unsafe (because of eval), raw_input should be preferred for critical applications.
Non-blocking, multi-threaded example:
As blocking on keyboard input (since the
input()
function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.This works by creating one thread to run in the background, continually calling
input()
and then passing any data it receives to a queue.In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.
1. Bare Python 3 code example (no comments):
2. Same Python 3 code as above, but with extensive explanatory comments:
Sample output:
References:
This should work
It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:
The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function
raw_input
:If you want to convert that to a number, then you should try:
... though you need to take into account that this can raise an exception:
And if you want to print the number using formatting, in Python 3
str.format()
is recommended:Instead of:
But both options (
str.format()
and%
) do work in both Python 2.7 and Python 3.try
and if you want to have a numeric value just convert it: