-2

I have some codes below, the choice takes only integer input but prints out something special if the input is not an integer. However, the codes below to treat this issue seems a little bit lengthy. Anyway to fix it?

from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(1)
    else:
        dead("You're greedy!")


def dead(why):
    print why, "Good job!"
    exit(0)

gold_room()
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Bratt Swan
  • 1,068
  • 3
  • 16
  • 28
  • This question is probably better suited to [Code Review Stack Exchange](https://codereview.stackexchange.com/). – Jordan Running Jan 29 '17 at 01:02
  • I presume you are talking about the rather lengthy if statement? Look at the built in function `any`. Regardless I would recommend doing the conversion to `int` then catching the exception if necessary (like the just deleted answer). – Paul Rooney Jan 29 '17 at 01:04
  • What if `choice == '1a'`? – Peter Wood Jan 29 '17 at 01:05
  • Also see http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values. – TigerhawkT3 Jan 29 '17 at 01:15

2 Answers2

6

Try something like:

try:
    how_much = int(choice)
except ValueError:
    dead('Man, learn to type a number.')

and look up Easier to ask for forgiveness than permission for the rationale.

Community
  • 1
  • 1
D.Shawley
  • 58,213
  • 10
  • 98
  • 113
0

You can use the str.isdigit() to check if its a number, using try...except statement for this is not recommended because it makes your code messy and could cause errors in the long run. But if it's only that it'll work too.

from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if choice.isdigit(): #Checks if it's a number
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")
        return

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(1)
    else:
        dead("You greedy bastard!")


def dead(why):
    print why, "Good job!"
    exit(0)

gold_room()
Taku
  • 31,927
  • 11
  • 74
  • 85