[Tutor] dealing with user input whose value I don't know

Bill Campbell bill at celestial.net
Thu Oct 2 19:54:56 CEST 2008


On Thu, Oct 02, 2008, Steve Willoughby wrote:
>On Fri, Oct 03, 2008 at 01:38:48AM +0800, David wrote:
>> Does that mean input() is obsolete (after all, Zelle's book is not the 
>> freshest on the shelf)? Or do they have different uses?
>
>Depends on how you look at it.
>
>input() automatically evaluates whatever the user types as a Python
>expression and returns the result.  So if they type 5, the integer
>5 is returned.  For your program, that's probably what you want, and
>has the advantage of letting you type something like 2+3 so your user
>can let Python evaluate math expressions.
>
>On the other hand, you'd think that you could ask a user for a text
>response using input():
>   name = input("What is your name? ")
>   print "Hello, ", name
>
>But if they just type the answer, Python will crash with an error
>because it's expecting a legal Python expression there (so a 
>string value would have to be typed in quotes).

Remember the cardinal rule NEVER TRUST USER INPUT!  Always check
for validity, and use methods that prevent malicious strings from
allowing the user to get unauthorized access or change things
they shouldn't.

Many of the common exploits of web pages are the result of poor
checking of input resulting in sql injection attacks, and other
breaches.

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186

There are three kinds of men. The ones that learn by reading. The few who
learn by observation.  The rest of them have to pee on the electric fence
for themselves. -- Will Rogers


More information about the Tutor mailing list