0

If the player types in any out of range or invalid values, I want it to loop back to ask him to place his bet again.

I can get this half-way working when I wrap raw_input with int().

However, if say the player accidentally typed a letter or just hit enter without typing anything, it would throw an error, thus stopping the game/script.

So if a player does make a mistake like that, I need it to loop back to "Place your bet" again instead of throwing an error and crashing the script.

def betAmount():
    if number_of_hands == 1:
        if chip_count_player1 > 0:
            global chips_bet
            chips_bet = raw_input("Place your bet!")
            if chips_bet in range(0, chip_count_player1 + 1):
                print "Your bet is within range"
            else:
                print "NOT IN RANGE"
                betAmount()
CRABOLO
  • 8,605
  • 39
  • 41
  • 68
  • 1
    You might want to have a look at this question asked yesterday: http://stackoverflow.com/questions/20540274/most-pythonic-way-to-do-input-validation/20540530#20540530 – Alfe Dec 13 '13 at 13:35

2 Answers2

1
  1. You need to convert the chips_bet to a number like this

    try:
        chips_bet = int(raw_input("Place your bet!"))
    except ValueError:
        betAmount()
    
  2. You are constructing a new list of numbers and then checking if the chips_bet is there in it or not. That is inefficient. You can check like this

    if 0 <= chips_bet <= chip_count_player1:
    
  3. The base idea can be implemented like this

    bet = getBet()
    ...
    def getBet(maximum):
        bet = -1
        while (bet < 0) or (bet > maximum):
            try:
                bet = int(raw_input("Place your bet!"))
            except ValueError: pass
        return bet
    
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

you can split your prompt/input/validate loop into a little function, and just call that (it's easier to separate the retry loop from the program logic)

For example, this won't throw, and will only return a validated number:

def safe_int_input(prompt, validate):
    while True:
        try:
            val = int(raw_input(prompt))
            if validate(val):
                return val
        except: pass
        print "invalid input"

and you'd call it like this:

chips_bet = safe_int_input("Place your bet! ",
                          lambda v:(v >= 0 and v <= chip_count_player1))
Useless
  • 64,155
  • 6
  • 88
  • 132