[Tutor] [Long]General Questions
Jeff Shannon
jeff at ccvcorp.com
Tue Aug 12 12:18:18 EDT 2003
gnux at freesurf.fr wrote:
>I've got a question concerning this prog: why have u written
>"radius=input()"rather than "radius=raw_input()"
>I thought we use the second when we ask something to the user
>Thx if u can explain me the difference between the two and why u
>use the second
>
Both input() and raw_input() prompt the user to type something, and
return that to the program. However, they handle what's typed a bit
differently.
raw_input() will always return a string, exactly as the user typed it.
input(), on the other hand, evaluates that string as if it were a
Python expression -- input() is equivalent to eval(raw_input()). This
makes input() more convenient for entering numbers, because you can just
type the number and get an integer (or float, or whatever), just as if
you'd typed a numeric literal in the interpreter. By comparison, with
raw_input(), you'd then have to use int() or float() to convert the
string into a number. On the other hand, input() is less convenient for
entering strings, because (just like a string literal in the
interpreter) you need to use quotes around it. And if the quotes are
forgotten, then whatever is typed is interpreted as a Python identifier,
which might look up an existing variable or might throw a NameError.
And since input() effectively executes an arbitrary expression, it
leaves you *wide* open to malicious (or accidental) attacks on your
computer system.
In short, input() should only be used when you know exactly what's going
to happen. Which, really, should only be when you're working in the
interactive interpreter. It's too dangerous for routine production use.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list