[Tutor] Which is safer and easier to code, raw_input or int(raw_input))?
alan.gauld at freenet.co.uk
Tue Jul 19 14:08:31 CEST 2005
> Subject: [Tutor] Which is safer and easier to code,raw_input or
val = int(raw_input())
is the same as
val = raw_input()
val = int(val)
in terms of safety because it is the same I/O mechanism. Arguably
the int() call around it makes it marginally safer since it throws an
that bit sooner. Both are much safer than using input(), which may be
you had in mind?
The int() wrapper may look like extra typing but if you include the
quote signs you need at every comparison without the int conversion it
rapidly evens out.
if val == '5':...
elif val == '7':...
as opposed to
if val == 5:...
elif val == 7:...
Also if you just capture the string its much harder to write control
logic to correct an invalid number entry (eg the user types 'four'
instead of '4', or even 'l'(ell) instead of '1') later than at the
time you prompt for it, again a lot of extra coding.
input() by comparison has so many opportunities to go wrong that,
except for small personal use programs, its a non starter. Its not
only malicious badness but using the example above, an ell instead
of a one would result in the program variable 'l' being evaluated.
'l' could be a list, a function object, a string, anything!
int(raw_input()) would detect the problem.
My 2 cents,
More information about the Tutor