[Tutor] Re: Suggestions for cleaner code

Jeff Shannon jeff@ccvcorp.com
Tue Jul 8 21:03:02 2003


Matt Richardson wrote:

>I'll get there one of these days....
>Can I ask why 'input' is frowned upon?  I noticed that in 'Core Python
>Programming' the method is as below, namely "int(raw_input())", but in
>the 'Non-programmer's' tutorial, 'input()' is used.  Just curious.
>  
>

That's a good question, actually.

The reason that input() is frowned upon is that it, in essence, executes 
Python code typed into it and returns the result of that execution.  If 
someone types a number, then you get a number (just like if you'd typed 
a numeric literal in a Python program).  However, if you want someone to 
type a word, then they'd need to enclose it in quotes, or else input() 
will throw a NameError -- or, if that word actually is a name used in 
your program, it could have unexpected side effects.  Even worse, 
someone could easily type something like 'import os; os.system("rm -s 
/")' -- this *will* import the os module and spawn a shell that will 
attempt to delete every file on your system.  (Hopefully, if you're 
running *nix, you'll have protections set so that this particular 
example won't do significant damage, but still...)

On the other hand, raw_input() will always return a string, and it 
*won't* evaluate anything so there's no danger of unexpected side 
effects.  It's pretty easy to convert that string into a number by using 
int(), though you may want to use a try/except structure just in case a 
user types something that's not a number.  

Jeff Shannon
Technician/Programmer
Credit International