0

I have the following piece of code:

choice = raw_input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

It seems like if "0" in choice or "1" in choice is used to determine whether the raw input choice is an integer or not. Why is it? I was just a bit curious. Many thanks for your time and attention.

EDIT. It seems like a similar question already exists. See How to check if string input is a number?. Many thanks for the following different answers here. What I was curious is: why can we use if "0" in choice or "1" in choice to determine whether the raw input is a number or not in python.

Community
  • 1
  • 1
ntough
  • 333
  • 1
  • 3
  • 8
  • 2
    It seems like an attempt at checking whether the `int()` call will succeed or generate an error. However, it would fail to catch invalid input like `'0qwer'`. It's easier to just use a `try..except` construct. – TigerhawkT3 Jul 20 '15 at 02:00

3 Answers3

1
#!python
try:
    choice = raw_input("> ")
except (EnvironmentError, EOFError), e:
    pass # handle the env error, such as EOFError or whatever
try:
    how_much = int(choice)
except ValueError, e:
    dead("Man, learn to type a number.")

It's also possible to enclose the input and conversion in a single, more complex try: block thus:

#!python
try:
    choice = int(raw_input('> '))
except (ValueError, EOFError, EnvironmentError), e:
    dead('Man, learn to type a number')
    print >> sys.stderr, 'Error: %s' % e

... here I've also shown one way to use the captured exception object to display the specific error message associated with that exception. (It's also possible to use this object in more advanced ways ... but this will suffice for simple error handling).

Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
0
choice = raw_input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

can not detect many numbers, such as 23.

How do I check if a string is a number (float) in Python? can help you.

Community
  • 1
  • 1
letiantian
  • 437
  • 2
  • 14
0

You may use isdigit() function.

choice = raw_input("> ")
if choice.isdigit():
    how_much = int(choice)
else:
    dead("Man, learn to type a number.")
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274