Python Forum

Full Version: Get input directly as a number?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In my little, amateurish Python routines, I often need to get a number as input, so I do:

Quote:num = input('just enter a number ')
startNum = int(num)

Today, I just thought, "Is it possible to get a number directly?"

Is it?
yes it is possible use the int function
example - int(input('enter a number '))
this way you can take a number directly as a input
Please use proper code tags while coding. You can do :
num = int(input("Just enter a number : "))
In python 2.7 and before the conversion was done automatically. In effect the old "input" was eval(raw_input(prompt)). So if I typed 1.23 input would return a float, enter 5 and you get an int, and enter abc you get something else.
var var = 'a variable'
while True:
    raw = input('Enter value ')
    cooked = eval(raw)
    print(raw, cooked, type(cooked))
A problem with this is you have to enter something that can be evaluated.
Output:
Enter value 1 1 1 <class 'int'> Enter value 2 2 2 <class 'int'> Enter value var var a variable <class 'str'> Enter value abc Traceback (most recent call last): File "C:\Users\djhys\Documents\Python\Musings\junk.py", line 5, in <module> cooked = eval(raw) File "<string>", line 1, in <module> NameError: name 'abc' is not defined
Python 3 gets around this problem by always returning a string and forcing us to do any required conversions. A far better approach in my opinion. Input is a very personal thing.

I hardly ever use input, but looking at all the posts in the forum I know I am a minority. If you use input a lot I think it worth spending some time and making a nice package of input functions. You could have input_int, input_float, input_number, input_imaginary, input_choice. You could have a default value that is returned if the entered input is not the right type. You could have a flag that keeps asking for input until a valid input is received. There are so many things that could be done once and then reused over and over instead of making the same mistakes over and over and over.