简体   繁体   中英

Checking for user error in Python

I am trying to analyse user input and only allow integers to be inputted. I have succesfully managed to only allow denominations of 100s between a certain range, but I cannot work out how to prompt the user to re-enter data if they enter a random string. Trying to use the "try" command just results in the program getting stuck:

while True:
  try:
    bet=int(raw_input('Place your bets please:'))
  except ValueError:
    print 'l2type'
#The following receives a betting amount from the user, and then assesses whether it is a legal bet or not. If not, the user is prompted to enter a legal bet.
while True:
 if bet%100==0 and 100<=bet<=20000:
    print bet,"Your bet has been accepted, can you make a million?"
    break
 else:
    print bet,"Please enter a legal bet. The table minimum is 100, with a maximum of 20000 in increments of 100."
    bet = input('Place your bets please:')

You have the right approach for rejecting non-integer input, but you need to break out of the loop if your user enters valid input. Use the break statement:

while True:
    try:
        bet=int(raw_input('Place your bets please:'))
        break # we only get here if the input was parsed successfully
    except ValueError:
        print 'l2type'

You will probably also want to move the range checks within the loop. If input that's out of range doesn't naturally lead to an exception, use if statements to make sure "break" is only executed if the input is completely valid.

I rather prefer my recursive version:

def ask_bet(prompt):
    bet = raw_input(prompt)

    # Validation. If the input is invalid, call itself recursively.
    try:
        bet = int(bet)
    except ValueError:
        return ask_bet('Huh? ')
    if bet % 100 != 0:
        return ask_bet('Huh? ')
    if not 100 <= bet <= 20000:
        return ask_bet('Huh? ')

    # The input is fine so return it.
    return bet

ask_bet("Place your bets please: ")

In my opinion, that is much cleaner and easier to read than while loops. You don't have to bother what are attribute values after the first iteration? Adding new validation rules is also really simple.

Generally, I try to avoid while loop in favour of recursive version. Of course, not all the time, since it's slower and the stack is not infinite.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM