0

In python 2.7, if we take an integer as input, which one is more faster and efficient or there is no difference at all:

input() or int(raw_input())

John Constantine
  • 1,038
  • 4
  • 15
  • 43
  • 1
    Set up a test and find out. Use the `time` module. – TigerhawkT3 Apr 14 '15 at 01:22
  • Ignoring timing, the former will not throw an error if you give it not an int. The latter makes more sense if you want to do a try/catch up front. – Dylan Lawrence Apr 14 '15 at 01:22
  • Or `timeit` module! Also, speed wouldn't be a big issue, the difference would be in microseconds. First options is basically `eval(raw_input())`, while second is `int(raw_input())` – Zizouz212 Apr 14 '15 at 01:23
  • Aren't both of these limited by the reaction of the CL user? What's the point? – jwilner Apr 14 '15 at 01:23
  • 1
    I guess it could add up if you're running it on a shared machine with many simultaneous users? Maybe? Probably not. Premature optimization, to be sure, but curiosity isn't bad. – TigerhawkT3 Apr 14 '15 at 01:24

1 Answers1

3

From the Python docs

input([prompt])

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

int(raw_input()) will be faster, more secure and produce less confusing results.

Consider:

>>> b = 5
>>> a = input()
[1, 2, 3]
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> a = int(raw_input())
[1, 2, 3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '[1, 2, 3]'

The ValueError raised when reading input is far more desirable than the TypeError raised when using the variable.

Community
  • 1
  • 1
Raniz
  • 10,882
  • 1
  • 32
  • 64
  • 1
    Nice answer! I would advocate for putting a small inline comment next to the input statements with what you typed in, like `a = input() # input: [1, 2, 3]`. Another important note is that `input` in python2 is a [liability](http://stackoverflow.com/a/7710959/4775429) -- I can type any python code into it and it'll be executed by the program. – Dan Apr 14 '15 at 01:46