CRABOLO
CRABOLO

Reputation: 8793

Validating user input to see if in range of numbers, if not loop back to ask for user input again

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()

Upvotes: 0

Views: 2723

Answers (2)

Useless
Useless

Reputation: 67723

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))

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

  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
    

Upvotes: 1

Related Questions