Python Forum
Get input directly as a number? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Get input directly as a number? (/thread-26545.html)



Get input directly as a number? - Pedroski55 - May-05-2020

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?


RE: Get input directly as a number? - anbu23 - May-05-2020

https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers


RE: Get input directly as a number? - MohammedSohail - May-05-2020

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


RE: Get input directly as a number? - pyzyx3qwerty - May-05-2020

Please use proper code tags while coding. You can do :
num = int(input("Just enter a number : "))



RE: Get input directly as a number? - deanhystad - May-05-2020

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.