-1

I finished my program of craps! now I seem to be able to break it very easily...

How would I check if a value is a int or float before I convert it from a string... I tried using ValueError: but I think because the function is not part of a loop I cant... Sorry first time I needed to think of this!

My code works great if the user actually follows directions(HA!) but will break if I enter something like "THREE" instead of 3. Code:

def parse_message(msg):

    if len(msg) >= 1:
        msg = msg.split(' ')
        options = {'!resetme': command_reset_player,
                   '!removebets': command_remove_bets}
        if msg[0] == '!bet':
            if msg[1] == 'place':
                if int(msg[2]) in [4, 5, 6, 8, 9, 10] :
                    if float(msg[3]) > 1:
                        UpdateBets.PlaceBet(sender, int(msg[2]), float(msg[3]))
            if msg[1] == 'pass':
                if float(msg[2]) > 1:
                    UpdateBets.PassBet(sender, float(msg[2]))
            if msg[1] == 'passodds':
                if float(msg[2]) > 1:
                    UpdateBets.PassOdds(sender, float(msg[2]))
            if msg[1] == 'hard':
               if int(msg[2]) in [4, 6, 8, 10] :
                   if float(msg[3]) > 1:
                       UpdateBets.HardBet(sender, int(msg[2]), float(msg[3]))
  • Why don't you define a function as in http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – 7hibault Mar 25 '16 at 22:19

1 Answers1

0
try:
    val = int(val)
except ValueError:
    print('Not an int')
Alec
  • 583
  • 3
  • 21
  • hmm so before every if that needs to be an int or float I run the loop with the except statement.... seems like it might work. – HELPMEPLEASE Mar 25 '16 at 22:26
  • Actually for the str->int conversion, you may be better off using `val.isdigit()` to test if the string is numeric - from a performance perspective, it likely depends on whether you expect to get mostly valid strings or not – Alec Mar 25 '16 at 22:30
  • `"-1".isdigit()` is considered false but `int("-1")` is completely valid, the way you have posted is the best, as is described in the various answers that this question is a dup of. – Tadhg McDonald-Jensen Mar 26 '16 at 04:11