Reputation: 1
Situation: I'm creating a "Casting of Lots" game for school. I have a function to validate the user's input for how much they want to "wager" this round. I want to catch all errors, while print out different error messages based on the error and ask for input again.
Problem: I caught every error, however, I can't seem to figure out how to loops my first try-except statement so that if an integer is entered twice, it will continue to catch the error.
Here's my code (the talents argument is going to be used later in the function):
def validate_wager(talents):
"""
Validates user input for wager, checks for strings, negatives, and excessively high numbers
"""
# formats wager request
print('{wager:-<34}'.format(wager="How much do you wish to wager? "), end=" ")
try:
# gets user input for wager, captures Type and Value
# errors, asks again
wager = int(input())
except:
wager = int(input('Wager must be a whole number: '))
# if wager is 0 or negative, prints error, asks again
while wager <= 0:
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be zero or negative: '))
except:
wager = int(input('Wager must be a non-negative, whole number: '))
# if wager is greater than remaining talents, prints error, asks again
while wager > int(talents):
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be more than remaining talents: '))
except:
wager = int(input('Wager must be a whole number and less than remaining talents: '))
return wager
This is the output for the first iteration after a string is entered once:
Welcome to the Lots Game
Talents you have to play with: 100
1 - Field Bet
2 - Pass Bet
3 - Quit
Choice --------------------------- 1
How much do you wish to wager? --- H
Wager must be a whole number:
The solution: If a string is entered again, the try-except statement will not catch it. I'd like it to repeat "Wager must be a whole number" until an integer is entered.
I've already tried nesting the try-except statement inside a while loop that updates a variable with "True" or "False" if the is or is not an error, but that didn't work. I've tried a number of other things as well, but I just can't seem to figure it out. Any help would be greatly appreciated.
Upvotes: 0
Views: 4546
Reputation: 54148
As all condition are based on wager
, use only one while True
loop, and break it only when all conditions are meet
while True:
try:
wager = int(input('Wager must be a number, strictly positive and less than remaining talents: '))
if 0 < wager < int(talents):
break
except ValueError:
print("Invalid number")
When you have multiples values to get frmo the user, use the while True
construction once per value
Upvotes: 1