[Tutor] Input checking [letters or numbers]
Panagiotis Atmatzidis
p.atmatzidis at gmail.com
Fri Dec 23 20:16:33 CET 2005
Hello there,
Thank you for the prompt response.
On 12/23/05, bob <bgailer at alum.rpi.edu> wrote:
> At 10:15 AM 12/23/2005, Panagiotis Atmatzidis wrote:
> >Hello,
> >
> >Can someone provide me with an error checking example about an x
> >variable that needs to be number only? I used something like:
> >
> > def useridf():
> > print ""
> > print "WARNING: If you don't understand why this must be unique,
> >exit and read the manual."
>
> You ask the user to exit but you don't tell him how to do that!
>
> > print ""
> > userid = input("x : ")
> >
> >I know that "input" accepts only numbers
>
> How did you "know" that? Try this:
> print input("x ; ")
> and enter "Hello world"
OSX atma ~ $ python
Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input("x: ")
x: hello world
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1
hello world
^
SyntaxError: unexpected EOF while parsing
Just did.. and as you can see I get an error. I know because I read so
in the tutorial I mentioned before.. I mean that it says so.. now I am
taking the first steps into programming, hence I don't really know if
there's another reason for input to break upon chars.
>>> x = input("x: ")
x: 12
>>>
>
> Truth is input() "accepts" anything and attempts to evaluate it as a
> Python expression. If that fails it raises an exception.
Okay.
>
> You should use raw_input() instead. This takes any input and returns
> it as a character string.
I already use raw_input for alphanumeric characters.
> x = raw_input("x : ")
> if x.isdigit(): # ensure input is a number
> y = int(x) # convert to integer
> else:
> print 'Boo"
Thank you for the sample code.
>
> >, but I don't want the program
> >to break if someone puts other chars in it. I want to, print "Only
> >numbers are accepted." which is easy. But still I can't understand how
> >to do the check using if/elif/else statements.
>
>
Best Regards,
Panagiotis
More information about the Tutor
mailing list