Help please

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Apr 1 20:09:43 EDT 2013


On Sun, 31 Mar 2013 22:41:32 -0700, khaosyt wrote:

> On Monday, April 1, 2013 1:24:52 AM UTC-4, Chris Angelico wrote:
>> On Mon, Apr 1, 2013 at 4:15 PM,  <khaosyt at gmail.com> wrote:
>> 
>> >     integer = input("Enter a positive integer: ")
>> 
>> >     again = raw_input("Again? (Y/N): ")
>> 
>> 
>> 
>> Okay, the first thing I'm going to say is: Don't use input() in Python
>> 
>> 2. It's dangerous in ways you won't realize. Use int(raw_input(...))

[...]

> Elaborate, please.


The input() function takes the user's text, and automatically evaluates 
it as if it were code. In the hands of a non-expert, that can lead to 
some unexpected errors:

py> answer = input("what is your name? ")
what is your name? Steve
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Steve' is not defined



But at least that gives you an error. It can also give you weird and 
unexpected results. Suppose my name was Lenny, and I did this:

py> answer = input("what is your name? ")
what is your name? len
py> print answer
<built-in function len>



Worse, because input evaluates text as code, it can do anything, 
including bad things:

py> answer = input("what is your name? ")
what is your name? 200**300**300
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
MemoryError


(while the above code was running, my computer got slower and slower and 
slower, and potentially it could have locked up completely).


So the general advice is, treat the input() function as For Experts Only, 
and always use raw_input() instead.




-- 
Steven



More information about the Python-list mailing list