Trying To Catch Invalid User Input
Victor Subervi
victorsubervi at gmail.com
Mon Aug 24 10:17:04 EDT 2009
That's nice. Thanks!
V
On Sun, Aug 23, 2009 at 5:02 PM, Dennis Lee Bieber <wlfraed at ix.netcom.com>wrote:
> On Sun, 23 Aug 2009 10:04:57 -0500, Victor Subervi
> <victorsubervi at gmail.com> declaimed the following in
> gmane.comp.python.general:
>
> > Hi;
> > I have the following:
> >
> > style = raw_input('What style is this? (1 = short, 2 = long): ')
> > flag = 0
> > while flag == 0:
> > if (style != 1) or (style != 2):
> > style = raw_input('There was a mistake. What style is this? (1 =
> short,
> > 2 = long): ')
> > else:
> > flag = 1
> >
> Ugh... Unless you are using an archaic version of Python, the
> language has support for booleans...
>
> done = False
> while not done:
> ...
> done = True
>
>
> You fail to convert the character input from raw_input into an
> integer for comparison... Oh, and you say the input is wrong if it is
> NOT 1 OR NOT 2... 1 is not 2, and 2 is not 1, so... even if you did
> convert to an integer, it would be rejected.
>
> Consider:
>
> -=-=-=-=-=-=-=-
> while True:
> charin = raw_input("What style is this? (1: short, 2: long): ")
> try:
> style = int(charin)
> except: #I know, should not use naked except clause
> print ("The input '%s' is not a valid integer value; try again"
> % charin)
> else:
> if style in (1, 2): break
> print ("The input value '%s' is not in the valid range; try
> again"
> % style)
> -=-=-=-=-=-=-=-
> {Watch out for line wraps}
> Works in Python 2.5
>
> E:\UserData\Dennis Lee Bieber\My Documents>python Script1.py
> What style is this? (1: short, 2: long): ab1
> The input 'ab1' is not a valid integer value; try again
> What style is this? (1: short, 2: long): 1a
> The input '1a' is not a valid integer value; try again
> What style is this? (1: short, 2: long): 12
> The input value '12' is not in the valid range; try again
> What style is this? (1: short, 2: long): 2
>
> E:\UserData\Dennis Lee Bieber\My Documents>
>
> --
> Wulfraed Dennis Lee Bieber KD6MOG
> wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090824/86f3400f/attachment-0001.html>
More information about the Python-list
mailing list