[Tutor] Re: Checking for int only

Andrei project5 at redrival.net
Tue Jun 29 02:37:50 EDT 2004

K J <game <at> gameweave.com> writes:

> I tried what you said and it work good but when you picked a different  char
> other than an int it would just say Please choose an number: and if you

How can my solution possibly say "Please choose a number" when that string
doesn't even apppear in the code? Here's an interactive session I did with 
my code:

Integer: sdfwefafe
  That was not an integer.
Integer: waefawef
  That was not an integer.
Integer: 3.324
  That was not an integer.
Integer: .23423
  That was not an integer.
Integer: 3

> messed up twice then it would say that is not an option. So I did some

It instructs you that the input is incorrect regardless of how many attempts you
do, see demonstration above. I'm not sure what code you have been running, but
it doesn't seem to be the one I posted. Are you sure you copied it correctly?

> fooling around with it and came up with this so that it will say that is not
> an option the first time.
> So thanks for the help.
> number = raw_input("Please choose an number: ")
> while True:
>     try:
>         number = int(number)
>         break
>     except:
>         print '  That is not an option.'
>         number = raw_input("Please choose an number: ")

Your solution is basically another way of writing exactly what I did, with the
added disadvantage of having to maintain the prompt string "please blabla..." in
two different places. The solution effectively combines the disadvantage of an
endless 'while True' loop (being the necessity to use "break", which has
arguable obsfucational qualities) with the disadvantage of a non-endless loop
(being that it requires initialization and therefore maintenance of a certain
piece of code in two different places).



Real contact info (decode with rot13):
cebwrpg5 <at> jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

> > Use try-except:
> >
> > while True:
> >     number = raw_input('Integer: ')
> >     try:
> >         number = int(number) # will fail if the input is non-numerical
> >         break # stop endless loop
> >     except: # int() failed -> not an integer
> >         print '  That was not an integer.'
> >
> > Above is assuming that you mean 'integer' when you write 'number'. If you
> > mean to include floats, try float() instead of int().

More information about the Tutor mailing list