[Tutor] dealing with user input whose value I don't know
steve at alchemy.com
Thu Oct 2 20:14:49 CEST 2008
On Fri, Oct 03, 2008 at 02:06:47AM +0800, David wrote:
> Cheers for the insights!
> However, I just found out that changing input() to raw_input() breaks my
Recall that we told you raw_input() returns a string, while
input() returns an integer if you typed an integer value.
So you need to convert the string of characters the user typed
into an integer value before using it as a number:
numbers = int(raw_input(...))
> This program takes the average of numbers you supply!!
> How many numbers do you want me to work with? 2
> You want me to take the average of 2 numbers.
> Please type the numbers, separated by commas: 1,2
> You want to know the average of the numbers: 1,2
> Traceback (most recent call last):
> File "avgInput.py", line 13, in <module>
> add = add + i
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
> **** End of process output ****
> The reason being, I take, that
> numbers = raw_input("Please type the numbers, separated by commas: ")
> also returns the comma (1,2) and thus the for loop can't cope...
> So should I therefore retain
> numbers = input("Please type the numbers, separated by commas: ") ?
> Otherwise I don't know (yet) what to do....
> Bill Campbell wrote:
> >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
> Tutor maillist - Tutor at python.org
Steve Willoughby | Using billion-dollar satellites
steve at alchemy.com | to hunt for Tupperware.
More information about the Tutor